Search code examples
javascriptjavaselenium-webdriver

How to use Javascript in Selenium in Java


I found out that JavaScript is not working at all in my Selenium Tests in Java. I do not know why. Any suggestions?

((JavascriptExecutor) driver).executeScript("return arguments[0].innerText", driver.findElement(By.cssSelector("[id$=main:domainsCounter]")));

The javascript works fine in the console of the browser.

in console of browser


Solution

  • Finally I found that is is possible and necessary to set options. Like this:

    ChromeOptions chromeOptions = new ChromeOptions();
    FirefoxOptions firefoxOptions = new FirefoxOptions();
    EdgeOptions edgeOptions = new EdgeOptions();
    chromeOptions.addArguments("--enable-javascript");
    firefoxOptions.addArguments("--enable-javascript");
    edgeOptions.addArguments("--enable-javascript");
    try {
        chromeDriver = new RemoteWebDriver(
                    new URL(getRemoteWebDriverUrl()),
                    chromeOptions);
        firefoxDriver = new RemoteWebDriver(
                    new URL(getRemoteWebDriverUrl()),
                    firefoxOptions);
        edgeDriver = new RemoteWebDriver(
                    new URL(getRemoteWebDriverUrl()),
                    edgeOptions);
    } catch (MalformedURLException e) {
        LOGGER.error("Test failed because url is wrong ", e);
    }