How to click an element in Selenium WebDriver using JavaScript?
Asked Answered
C

12

52

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?

Cardiograph answered 14/8, 2012 at 7:41 Comment(1)
I don't get it - you want the .click() to fire javascript function binded to that button? Or do you need something like code.google.com/p/selenium/wiki/…?Cheka
C
117

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.

Chee answered 14/8, 2012 at 15:49 Comment(6)
May I know why arguments[0].click();? How do you know it is index 0?Rafaelof
Because you're passing in the element reference as the 0th argument in the executeScript call.Chee
Thanks for this, just spent the entire morning searching for a good solution and this works like a charm.Ascertain
I am trying to perform click action on a webElement in safari browser but not able to get this done. Code is able to trace the element, read the text of the webelement but click is not performed. There is no exception or error also. How can I perform? The above solution is also not working.Pericope
This works for me. There exception i have been getting is because the HTML page was not load completely, i put more time on Thread.Sleep(); then its working for me.ThanksOnstage
@Chee When JS.executeScript click can not work ? I do facing issue for some of the elements, executeScript returned null value for some elements only.Ebbarta
C
7

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();");
Cardiograph answered 14/8, 2012 at 8:13 Comment(5)
There is 6 people have voted up the answer,but it is not working for me.Getting This is not a function... exception. Even can not execute the script on console, there should not be semicolon after click().Onstage
This works for me. There exception i have been getting is because the HTML page was not load completely, i put more time on Thread.Sleep(); then its working for me.ThanksOnstage
It will work when we have "id" as locator. What If I have xpath as locator?Scaffolding
@Onstage DO NOT use Thread.sleep(). Instead, you should use either WebDriverWait or set up a page load time on your web driver. The idea is that, if the page loads in less than a second, you don't have to wait (for example) 10 seconds for your Thread.sleep() to allow your thread to resume,Pubes
Yes, It's standard to use WebDriverWait instead of Thread.sleep()Cardiograph
J
6

I know this isn't JavaScript, but you can also physically use the mouse-click to click a dynamic Javascript anchor:

public static void mouseClickByLocator( String cssLocator ) {
     String locator = cssLocator;
     WebElement el = driver.findElement( By.cssSelector( locator ) );
     Actions builder = new Actions(driver);
     builder.moveToElement( el ).click( el );
     builder.perform();
}
Julius answered 18/12, 2012 at 17:59 Comment(0)
H
5

Not sure OP answer was really answered.

var driver = new webdriver.Builder().usingServer('serverAddress').withCapabilities({'browserName': 'firefox'}).build();

driver.get('http://www.google.com');
driver.findElement(webdriver.By.id('gbqfb')).click();
Halpin answered 16/6, 2013 at 19:30 Comment(0)
R
3

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.

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.document.getElementById('gbqfb').click()");
Ruttger answered 14/8, 2012 at 8:18 Comment(2)
Is it possible to use WebDriver without instantiation? driver object must be initialized as driver = new FirefoxDriver(); Only declaration is not enough.Cardiograph
Yes indeed: I chose not to add the instantiation (hence the comment) because you might want to instantiate a driver from different browsers.Ruttger
A
1

By XPath: inspect the element on target page, copy Xpath and use the below script:worked for me.

WebElement nameInputField = driver.findElement(By.xpath("html/body/div[6]/div[1]/div[3]/div/div/div[1]/div[3]/ul/li[4]/a"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", nameInputField);
Assegai answered 9/8, 2018 at 5:9 Comment(1)
It's better to use Relative XPath instead of Absolute XPath.Cardiograph
E
1
const {Builder, By, Key, util} = require('selenium-webdriver')

// FUNÇÃO PARA PAUSA
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function example() {

    // chrome
    let driver = await new Builder().forBrowser("firefox").build()
    await driver.get('https://www.google.com.br')
    // await driver.findElement(By.name('q')).sendKeys('Selenium' ,Key.RETURN)

    await sleep(2000)

    await driver.findElement(By.name('q')).sendKeys('Selenium')

    await sleep(2000)

    // CLICAR
    driver.findElement(By.name('btnK')).click()


}
example()

Com essas últimas linhas, você pode clicar !

Equalitarian answered 5/5, 2020 at 3:36 Comment(0)
L
0

This code will perform the click operation on the WebElement "we" after 100 ms:

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

jse.executeScript("var elem=arguments[0]; setTimeout(function() {elem.click();}, 100)", we);
Leonoraleonore answered 1/2, 2017 at 9:54 Comment(4)
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. From reviewConscientious
This code will perform the click operation on the WebElement "we" after (100/1000) seconds.Leonoraleonore
I'd like to know why somebody would downvote this answer.Leonoraleonore
It likely got downvoted because it needed more information. Instead of leaving the requested explanation as a comment, you can edit your own post.Dacoit
N
0

Another easiest solution is to use Key.RETUEN

Click here for solution in detail

driver.findElement(By.name("q")).sendKeys("Selenium Tutorial", Key.RETURN);

Nemesis answered 11/3, 2020 at 23:32 Comment(0)
M
0

Use the code below, which worked for me:

public void sendKeysJavascript() {
  String file = getfile();
  WebElement browser = driver.findElement(By.xpath("//input[@type='file']"));
  JavascriptExecutor js = (JavascriptExecutor) driver;
  actionClass.waitforSeconds(5);
  js.executeScript("arguments[0].click();", browser);
  actionClass.waitforSeconds(1);
  browser.sendKeys(file);
}
String getfile() {
  return new File("./src/main/resources/TestData/example.pdf").getAbsolutePath();
}

Don't forget to add wait time before the js click action. It is mandatory

Madlynmadman answered 30/5, 2022 at 9:39 Comment(0)
M
0

I think some parts of above codes has changed a little, I'm learning Selenium with JavaScript and I founded 2 options to click

To start we need to find the element we want to click, could be By (id, class, etc.), here is how, https://www.youtube.com/watch?v=BQ-9e13kJ58&list=PLZMWkkQEwOPl0udc9Dap2NbEAkwkdOTV3.

Right down are the 2 ways that I'm talking about:


FIRST Method: 
await driver.findElement(By.id("sampletodotext")).sendKeys("Learning Selenium", Key.RETURN);

- Here we found an empty field by it's Id, and then we write "Learning Selenium" in this field with the sendKeys().
- Key.RETURN: Simulate the person pressing the ENTER key in keyboard.

SECOND Method: 
await driver.findElement(By.id("sampletodotext")).sendKeys("Learn Selenium");
    await driver.findElement(By.id("addbutton")).click().finally();

- The difference here, is we switched the Key.RETURN of the FIRST method, for the entire second line, in the SECOND method.
Maloriemalory answered 1/6, 2022 at 18:2 Comment(0)
M
-13

Cross browser testing java scripts

public class MultipleBrowser {

    public WebDriver driver= null;
    String browser="mozilla";
    String url="https://www.omnicard.com";

    @BeforeMethod
    public void LaunchBrowser() {

        if(browser.equalsIgnoreCase("mozilla"))
            driver= new FirefoxDriver();
        else if(browser.equalsIgnoreCase("safari"))
            driver= new SafariDriver();
        else if(browser.equalsIgnoreCase("chrome"))
            //System.setProperty("webdriver.chrome.driver","/Users/mhossain/Desktop/chromedriver");
            driver= new ChromeDriver(); 
        driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
        driver.navigate().to(url);
    }

}

but when you want to run firefox you need to chrome path disable, otherwise browser will launch but application may not.(try both way) .

Messick answered 23/9, 2014 at 17:53 Comment(1)
This does not answer the question because the question asks how to do it from within JavaScript, not Java.Overbear

© 2022 - 2024 — McMap. All rights reserved.