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?
The click() method simulates a mouse-click on an element. This method can be used to execute a click on an element as if the user manually clicked on it.
We can use the JavaScript Executor in Selenium to click an element. Selenium can execute JavaScript commands with the help of the method executeScript. Sometimes while clicking a link, we get the IllegalStateException, to avoid this exception, the JavaScript executor is used instead of the method click.
Selenium is an open-source automation testing tool that supports a number of scripting languages like C#, Java, Perl, Ruby, JavaScript, etc.
We can read Javascript variables with Selenium webdriver. Selenium can run Javascript commands with the help of executeScript method. The Javascript command to be executed is passed as an argument to the method. Also we have to add the statement import org.
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.
Here is the code using JavaScript to click the button in WebDriver:
WebDriver driver = new FirefoxDriver(); JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("document.getElementById('gbqfb').click();");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With