[java] How to use JavaScript with Selenium WebDriver Java

I want to use JavaScript with WebDriver (Selenium 2) using Java.

I've followed some a guide and on Getting Started page: there is an instruction at 1st line to run as:

$ ./go webdriverjs

My question: From which folder/location the command mentioned above will be run/executed?

This question is related to java javascript selenium-webdriver

The answer is


JavaScript With Selenium WebDriver

Selenium is one of the most popular automated testing suites. Selenium is designed in a way to support and encourage automation testing of functional aspects of web based applications and a wide range of browsers and platforms.

    public static WebDriver driver;
    public static void main(String[] args) {
        driver = new FirefoxDriver(); // This opens a window    
        String url = "----";


        /*driver.findElement(By.id("username")).sendKeys("yashwanth.m");
        driver.findElement(By.name("j_password")).sendKeys("yashwanth@123");*/

        JavascriptExecutor jse = (JavascriptExecutor) driver;       
        if (jse instanceof WebDriver) {
            //Launching the browser application
            jse.executeScript("window.location = \'"+url+"\'");
jse.executeScript("document.getElementById('username').value = \"yash\";");
// Tag having name then
driver.findElement(By.xpath(".//input[@name='j_password']")).sendKeys("admin");


//Opend Site and click on some links. then you can apply go(-1)--> back  forword(-1)--> front.
//Refresheing the web-site. driver.navigate().refresh();            
jse.executeScript("window.history.go(0)");
            jse.executeScript("window.history.go(-2)");
            jse.executeScript("window.history.forward(-2)");

            String title = (String)jse.executeScript("return document.title");
            System.out.println(" Title Of site : "+title);

            String domain = (String)jse.executeScript("return document.domain");
            System.out.println("Web Site Domain-Name : "+domain);

            // To get all NodeList[1052] document.querySelectorAll('*');  or document.all
            jse.executeAsyncScript("document.getElementsByTagName('*')");

            String error=(String) jse.executeScript("return window.jsErrors");
            System.out.println("Windowerrors  :   "+error);



            System.out.println("To Find the input tag position from top"); 
            ArrayList<?> al =  (ArrayList<?>) jse.executeScript(
                    "var source = [];"+
                    "var inputs = document.getElementsByTagName('input');"+
                    "for(var i = 0; i < inputs.length; i++) { " +
                       "   source[i] = inputs[i].offsetParent.offsetTop" +      //"    inputs[i].type = 'radio';"
                    "}"+
                    "return source"                 
                    );//inputs[i].offsetParent.offsetTop     inputs[i].type

            System.out.println("next");
            System.out.println("array : "+al);

            // (CTRL + a) to access keyboard keys. org.openqa.selenium.Keys 
            Keys k = null;
            String selectAll = Keys.chord(Keys.CONTROL, "a");
            WebElement body = driver.findElement(By.tagName("body"));
            body.sendKeys(selectAll);

            // Search for text in Site. Gets all ViewSource content and checks their.
            if (driver.getPageSource().contains("login")) {
                System.out.println("Text present in Web Site");
            }

        Long clent_height = (Long) jse.executeScript("return document.body.clientHeight");
        System.out.println("Client Body Height : "+clent_height);

        // using selenium we con only execute script but not JS-functions.

    }
    driver.quit(); // to close browser
}

To Execute User-Functions, Writing JS in to a file and reading as String and executing it to easily use.

Scanner sc = new Scanner(new FileInputStream(new File("JsFile.txt")));
        String js_TxtFile = ""; 
            while (sc.hasNext()) {          
                String[] s = sc.next().split("\r\n");   
                for (int i = 0; i < s.length; i++) {
                    js_TxtFile += s[i];
                    js_TxtFile += " ";
                }           
            }
        String title =  (String) jse.executeScript(js_TxtFile);
        System.out.println("Title  : "+title);

document.title & document.getElementById() is a property/method available in Browsers.

JsFile.txt

var title = getTitle();
return title;

function getTitle() {
    return document.title;
}

If you want to read text of any element using javascript executor, you can do something like following code:

WebElement ele = driver.findElement(By.xpath("//div[@class='infaCompositeViewTitle']"));
String assets = (String) js.executeScript("return arguments[0].getElementsByTagName('span')[1].textContent;", ele);

In this example, I have following HTML fragment and I am reading "156".

<div class="infaCompositeViewTitle">
   <span>All Assets</span>
   <span>156</span>
</div>

I had a similar situation and solved it like this:

WebElement webElement = driver.findElement(By.xpath(""));
webElement.sendKeys(Keys.TAB);
webElement.sendKeys(Keys.ENTER);

Following code worked for me:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.springframework.beans.factory.annotation.Autowired;

public class SomeClass {

    @Autowired
    private WebDriver driver;

     public void LogInSuperAdmin() {
        ((JavascriptExecutor) driver).executeScript("console.log('Test test');");
     }
}

You can also try clicking by JavaScript:

WebElement button = driver.findElement(By.id("someid"));
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].click();", button);

Also you can use jquery. In worst cases, for stubborn pages it may be necessary to do clicks by custom EXE application. But try the obvious solutions first.


I didn't see how to add parameters to the method call, it took me a while to find it, so I add it here. How to pass parameters in (to the javascript function), use "arguments[0]" as the parameter place and then set the parameter as input parameter in the executeScript function.

    driver.executeScript("function(arguments[0]);","parameter to send in");

You need to run this command in the top-level directory of a Selenium SVN repository checkout.


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