Skip to content
CodeKruPro

JavaScript Executor - Get Values

58/70

JavaScript Executor - Get Values

JavascriptExecutor lets you execute JavaScript directly in the browser. Cast the driver to execute JS:

JavascriptExecutor js = (JavascriptExecutor) driver;

A script only hands a value back to Java when it uses the return keyword; without it, executeScript() returns null.

Task:

  1. Navigate to https://testkru.com/Elements/TextFields
  2. Run a script with executeScript() that returns the page title from the document object
  3. Run a second script that finds the input with id preFilledTextField and returns its current value
  4. Print both values

Expected output:

JS Title: Text Fields
JS Value: Codekru

About this lesson

JavascriptExecutor in Selenium Java: run JavaScript with executeScript() and read the result

Learn Selenium JavaAdvancedJavaScript Executor

How it works

JavascriptExecutor is an interface that ChromeDriver and the other drivers implement. Casting the driver to it gives you executeScript(), which runs a piece of JavaScript in the current page and hands the result back to Java.

Only what the script returns comes back. A script without return gives null, even if the expression has a value. JavaScript values are converted on the way: whole numbers arrive as Long, decimals as Double, booleans as Boolean, DOM elements as WebElement, arrays as List and plain objects as Map. undefined becomes null.

Java values can be passed in. Extra arguments to executeScript() appear in the script as arguments[0], arguments[1] and so on, and a WebElement passed this way arrives as the real DOM element. A script that fails throws JavascriptException, for example "javascript error: nope is not defined".

About the assignment

The starter casts the driver for you. You run two short scripts on Text Fields, one that returns the document's title and one that returns the live value of the pre-filled field, and print what each returns.

What you will do

  1. Call js.executeScript() with a script that returns document.title, and print the result after the label JS Title:.
  2. Call it again with a script that finds the field by id with document.getElementById() and returns its value.
  3. Print that result after the label JS Value:.

Common mistakes

  • Leaving out return

    The script runs, but executeScript() gives back null, so the line prints the word null after the label.

  • Casting the result to the wrong type

    A number comes back as Long, not Integer. Casting it to Integer throws ClassCastException.

  • Reading the value attribute in JavaScript

    The DOM's own getAttribute() method, asked for value inside the script, returns the HTML default, while .value returns what the field holds now. After typing into the field they differ.

In a real test suite

Tests use JavaScript to read state that WebDriver has no call for: localStorage entries, values on window that an app exposes for testing, or whether a page has finished an animation. Use it to read and to set up; keep user actions in normal WebDriver calls so the test still behaves like a user.

Lesson 57 typed with Actions. The next lessons use executeScript() to scroll, to click and to change the page.

To try one of these calls on any page without a task, open the Online Selenium Java Compiler.

Starter code

The editor above opens with this code. Fill in the TODO lines, then run and submit it.

Main.java
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class Main {
    public static void main(String[] args) throws Exception {
        WebDriver driver = new ChromeDriver();
        driver.get("https://testkru.com/Elements/TextFields");
        
        JavascriptExecutor js = (JavascriptExecutor) driver;
        
        // TODO: Execute JS to get document.title
        // TODO: Execute JS to get preFilledTextField value
        // TODO: Print both
        
        driver.quit();
    }
}