Ripon Al Wasim
Ripon Al Wasim

Reputation: 37816

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.

driver.findElement(By.id("gbqfb")).click();

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

Upvotes: 53

Views: 512801

Answers (12)

Madan reddy
Madan reddy

Reputation: 1

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

Upvotes: 0

MouraCass
MouraCass

Reputation: 11

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.

Upvotes: 0

JimEvans
JimEvans

Reputation: 27496

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.

Upvotes: 118

Rafael Garcia
Rafael Garcia

Reputation: 11

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 !

Upvotes: 1

Muneeb Akhtar
Muneeb Akhtar

Reputation: 107

Another easiest solution is to use Key.RETUEN

Click here for solution in detail

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

Upvotes: 0

Jyothi M
Jyothi M

Reputation: 11

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

Upvotes: 1

hemanto
hemanto

Reputation: 2048

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

Upvotes: 0

Stilltorik
Stilltorik

Reputation: 1692

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()");

Upvotes: 3

Mofazzal Hossain
Mofazzal Hossain

Reputation: 37

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

Upvotes: -13

Dale
Dale

Reputation: 61

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();

Upvotes: 5

djangofan
djangofan

Reputation: 29689

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();
}

Upvotes: 6

Ripon Al Wasim
Ripon Al Wasim

Reputation: 37816

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();");

Upvotes: 7

Related Questions