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?

Deepak Rai
  • 2,163
  • 3
  • 21
  • 36
Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
  • I don't get it - you want the `.click()` to fire javascript function binded to that button? Or do you need something like http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_How_do_I_execute_Javascript_directly? – WTK Aug 14 '12 at 07:57

12 Answers12

115

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.

John Smith
  • 7,243
  • 6
  • 49
  • 61
JimEvans
  • 27,201
  • 7
  • 83
  • 108
  • 2
    May I know why `arguments[0].click();`? How do you know it is index 0? – huahsin68 Oct 01 '13 at 10:30
  • 6
    Because you're passing in the element reference as the 0th argument in the `executeScript` call. – JimEvans Oct 01 '13 at 12:37
  • 1
    Thanks for this, just spent the entire morning searching for a good solution and this works like a charm. – Jon Carlstedt Dec 23 '13 at 10:54
  • 4
    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. – Khushboo Jun 10 '15 at 05:48
  • 1
    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.Thanks – Almett Jun 23 '16 at 06:42
  • @JimEvans When JS.executeScript click can not work ? I do facing issue for some of the elements, executeScript returned null value for some elements only. – Ishita Shah Dec 04 '18 at 11:33
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();");
Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
  • 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()`. – Almett Jun 22 '16 at 07:29
  • 1
    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.Thanks – Almett Jun 23 '16 at 06:41
  • It will work when we have "id" as locator. What If I have xpath as locator? – Vinaykumar Patel Apr 13 '17 at 06:23
  • 1
    @Almett 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, – hfontanez Sep 18 '19 at 17:14
  • Yes, It's standard to use WebDriverWait instead of Thread.sleep() – Ripon Al Wasim Sep 19 '19 at 05:03
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();
}
djangofan
  • 28,471
  • 61
  • 196
  • 289
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();
Franz Kafka
  • 10,623
  • 20
  • 93
  • 149
Dale
  • 61
  • 1
  • 1
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()");
angryip
  • 2,140
  • 5
  • 33
  • 67
Stilltorik
  • 1,662
  • 4
  • 19
  • 31
  • Is it possible to use WebDriver without instantiation? driver object must be initialized as driver = new FirefoxDriver(); Only declaration is not enough. – Ripon Al Wasim Aug 14 '12 at 08:36
  • Yes indeed: I chose not to add the instantiation (hence the comment) because you might want to instantiate a driver from different browsers. – Stilltorik Aug 15 '12 at 07:29
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);
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Jyothi M
  • 11
  • 1
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 !

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);
MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
hemanto
  • 1,900
  • 17
  • 16
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) 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 review](https://stackoverflow.com/review/low-quality-posts/15068687) – Ferrybig Feb 01 '17 at 11:56
  • This code will perform the click operation on the WebElement "we" after (100/1000) seconds. – hemanto Feb 01 '17 at 12:19
  • I'd like to know why somebody would downvote this answer. – hemanto Feb 01 '17 at 17:18
  • 1
    It likely got downvoted because it needed more information. Instead of leaving the requested explanation as a comment, you can edit your own post. – Stephen Rauch Feb 01 '17 at 20:20
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);

Muneeb Akhtar
  • 87
  • 3
  • 11
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

Laurel
  • 5,965
  • 14
  • 31
  • 57
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.
MouraCass
  • 11
  • 2
-14

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) .