How to click an element in Selenium WebDriver using JavaScript


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.


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

This question is tagged with java javascript button click selenium-webdriver

~ Asked on 2012-08-14 07:41:16

The Best Answer is


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("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.

~ Answered on 2012-08-14 15:49:49


Here is the code using JavaScript to click the button in WebDriver:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;

~ Answered on 2012-08-14 08:13:50

Most Viewed Questions: