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?
Not sure OP answer was really answered.
You can't use WebDriver to do it in JavaScript, as WebDriver is a Java tool. However, you can execute JavaScript from Java using WebDriver, and you could call some JavaScript code that clicks a particular button.
By XPath: inspect the element on target page, copy Xpath and use the below script:worked for me.
I know this isn't JavaScript, but you can also physically use the mouse-click to click a dynamic Javascript anchor:
This code will perform the click operation on the
WebElement
"we" after 100 ms: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 invokeswindow.alert()
, you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use theJavascriptExecutor
class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.You should also note that you might be better off using the
click()
method of theWebElement
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.