How to click an element in Selenium WebDriver using JavaScript

Ripon Al Wasim picture Ripon Al Wasim · Aug 14, 2012 · Viewed 347.6k times · Source

I have the following HTML:

<button name="btnG" class="gbqfb" aria-label="Google Search" id="gbqfb"><span class="gbqfi"></span></button>

My following code for clicking "Google Search" button is working well using Java in WebDriver.

driver.findElement(By.id("gbqfb")).click();

I want to use JavaScript with WebDriver to click the button. How can I do it?

Answer

JimEvans picture JimEvans · Aug 14, 2012

Executing a click via JavaScript has some behaviors of which you should be aware. If for example, the code bound to the onclick event of your element invokes window.alert(), you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.

// Assume driver is a valid WebDriver instance that
// has been properly instantiated elsewhere.
WebElement element = driver.findElement(By.id("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);

You should also note that you might be better off using the click() method of the WebElement interface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.