[java] 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?

This question is related to java javascript button click selenium-webdriver

The answer is


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


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

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

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 !


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

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

Another easiest solution is to use Key.RETUEN

Click here for solution in detail

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


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

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click

Examples related to click

Javascript Click on Element by Class HTML/Javascript Button Click Counter Angularjs action on click of button python selenium click on button Add and remove a class on click using jQuery? How to get the id of the element clicked using jQuery Why is this jQuery click function not working? Play sound on button click android $(document).on("click"... not working? Simulate a click on 'a' element using javascript/jquery

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java