What is JavaScriptExecutor

Running JavaScript in the Page

JavascriptExecutor is an interface that ChromeDriver and the other drivers implement. It runs a piece of JavaScript inside the current page and returns the result to Java.

import org.openqa.selenium.JavascriptExecutor;

JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("return document.title;");
Long width = (Long) js.executeScript("return window.innerWidth;");
System.out.println(title + " / " + width + " px");

Example

Output:

Run JsBasicsTest.main()

Example output

ShopEase - Online Shopping for Electronics, Fashion and More / 1366 px

Return Types

JavaScript returnsJava receives
number (integer)Long
number (decimal)Double
string / booleanString / Boolean
a DOM elementWebElement
array / objectList<Object> / Map<String, Object>
nothing (no return)null

Note: Pass Java values into the script with arguments[0], arguments[1], ...: js.executeScript("arguments[0].click();", element).