Using JavaScriptExecutor in Selenium: Unlocking Advanced Web Interactions

Selenium is one of the most popular and widely used automation test suites to automate web applications. It can perform from very basic to advanced actions on a web page, such as clicking on a button, sending text in the input field, selecting an item from a drop down, performing mouse-keyboard actions, etc. However, there are instances when Selenium WebDriver cannot interact with certain web elements and that is when JavascriptExecutor is used! What is JavascriptExecutor in Selenium? JavascriptExecutor is an interface that facilitates a mechanism to execute JavaScript through Selenium WebDriver. This interface provides various methods to run JavaScript on the selected window or the current web page. Selenium WebDriver supports different language bindings and JavascriptExecutor is available in each of those bindings. JavaScript is a programming language that interacts with HTML in a web browser and to do so JavaSciptExecutor interface is required. To use JavaSciptExecutor interface with Selenium, import the following package: org.openqa.selenium.JavascriptExecutor; JavascriptExecutor provides the following two methods to interact with web elements using Selenium WebDriver: 1.executeScript(): This method executes JavaScript in the context of the currently selected window or frame through the browser. The script will be executed as the body of an anonymous function and the control is returned only after the script is finished. In other words, it means the script will run and return immediately with the result. You should use this method when you want to execute simple and quick JS commands like clicking an element, scrolling, reading a value, etc. Example: JavascriptExecutor js = (JavascriptExecutor) driver; String title = (String) js.executeScript("return document.title;"); System.out.println("Page title is: " + title); 2.executeAsyncScript(): This method executes an asynchronous piece of JavaScript in the context of the currently selected window or frame in Selenium. This method is mostly used for handling asynchronous operations like waiting for AJAX calls to complete which means it waits until a callback is invoked. You should use this method when you are dealing with setTimeout, AJAX or any asynchronous operation. js.executeAsyncScript( "var callback = arguments[arguments.length - 1];" + "setTimeout(function(){ callback('Async script executed'); }, 1000);" ); Why use JavaScriptExecutor in Selenium? JavascriptExecutor is used in Selenium when the standard WebDriver methods like click(), sendKeys(), etc are not capable of performing the desired actions on the web element due to various reasons. Below are some of the scenarios when you should use JavascriptExecutor in Selenium: 1. Scroll the web page: Selenium does not have any dedicated built-in function to programmatically scroll web pages. This can be achieved through the use of JavascriptExecutor only. 2. To handle non-interactable elements: Some elements might be hidden or disabled due to dynamic rendering of the web page and with Selenium’s click method you may face ElementNotInteractableException. In such a scenario, you may use JavaScript which would directly interact with the DOM to bypass this. 3. To handle Mouse events: For some web elements especially those controlled by complex JavaScript frameworks, standard Selenium Actions methods like hover or drag-drop may not work properly. JavascriptExecutor may be used in such instances to simulate mouse events by dispatching events directly through the DOM. 4. DOM manipulation: For testing and debugging purposes, you may dynamically change styles, attributes or insert/remove elements using JavascriptExecutor. Working of JavascriptExecutor in Selenium Every web browser has a built-in JavaScript engine, like Chrome has V8 and Firefox has SpiderMonkey. Selenium WebDriver interacts with the browser via its specific driver, such as ChromeDriver for Chrome and FireFoxDriver for Firefox. When you use JavascriptExecutor, Selenium sends the JS code to the browser’s JS engine for execution. Syntax: JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(script, arguments); Commands for using JavascriptExecutor in Selenium JavascriptExecutor can be used to simulate various actions such as clicking, scrolling, getting and setting text, refreshing the page, etc. First you need to import the JavascriptExecutor interface, create a reference to it, and then call its methods. //import the package import org.openqa.selenium.JavascriptExecutor; //create a reference variable JavascriptExecutor js = (JavascriptExecutor) driver; //call the method js.executeScript(script, args); Below are some of the most common commands to handle such scenarios using JavascriptExecutor Interface. 1.To click a button: Syntax: js.executeScript(“document.getElementById(‘element id’).click();”); OR js.executeScript(“argum

May 8, 2025 - 12:13
 0
Using JavaScriptExecutor in Selenium: Unlocking Advanced Web Interactions

Selenium is one of the most popular and widely used automation test suites to automate web applications. It can perform from very basic to advanced actions on a web page, such as clicking on a button, sending text in the input field, selecting an item from a drop down, performing mouse-keyboard actions, etc. However, there are instances when Selenium WebDriver cannot interact with certain web elements and that is when JavascriptExecutor is used!

What is JavascriptExecutor in Selenium?

JavascriptExecutor is an interface that facilitates a mechanism to execute JavaScript through Selenium WebDriver. This interface provides various methods to run JavaScript on the selected window or the current web page. Selenium WebDriver supports different language bindings and JavascriptExecutor is available in each of those bindings. JavaScript is a programming language that interacts with HTML in a web browser and to do so JavaSciptExecutor interface is required.

To use JavaSciptExecutor interface with Selenium, import the following package:

org.openqa.selenium.JavascriptExecutor;

JavascriptExecutor provides the following two methods to interact with web elements using Selenium WebDriver:

1.executeScript(): This method executes JavaScript in the context of the currently selected window or frame through the browser. The script will be executed as the body of an anonymous function and the control is returned only after the script is finished. In other words, it means the script will run and return immediately with the result.

You should use this method when you want to execute simple and quick JS commands like clicking an element, scrolling, reading a value, etc.

Example:

JavascriptExecutor js = (JavascriptExecutor) driver;
String title = (String) js.executeScript("return document.title;");
 System.out.println("Page title is: " + title);

2.executeAsyncScript(): This method executes an asynchronous piece of JavaScript in the context of the currently selected window or frame in Selenium. This method is mostly used for handling asynchronous operations like waiting for AJAX calls to complete which means it waits until a callback is invoked.

You should use this method when you are dealing with setTimeout, AJAX or any asynchronous operation.

js.executeAsyncScript(
"var callback = arguments[arguments.length - 1];" +
"setTimeout(function(){ callback('Async script executed'); }, 1000);"
);

Why use JavaScriptExecutor in Selenium?

JavascriptExecutor is used in Selenium when the standard WebDriver methods like click(), sendKeys(), etc are not capable of performing the desired actions on the web element due to various reasons.

Below are some of the scenarios when you should use JavascriptExecutor in Selenium:

1. Scroll the web page: Selenium does not have any dedicated built-in function to programmatically scroll web pages. This can be achieved through the use of JavascriptExecutor only.

2. To handle non-interactable elements: Some elements might be hidden or disabled due to dynamic rendering of the web page and with Selenium’s click method you may face ElementNotInteractableException. In such a scenario, you may use JavaScript which would directly interact with the DOM to bypass this.

3. To handle Mouse events: For some web elements especially those controlled by complex JavaScript frameworks, standard Selenium Actions methods like hover or drag-drop may not work properly. JavascriptExecutor may be used in such instances to simulate mouse events by dispatching events directly through the DOM.

4. DOM manipulation: For testing and debugging purposes, you may dynamically change styles, attributes or insert/remove elements using JavascriptExecutor.

Working of JavascriptExecutor in Selenium

Every web browser has a built-in JavaScript engine, like Chrome has V8 and Firefox has SpiderMonkey. Selenium WebDriver interacts with the browser via its specific driver, such as ChromeDriver for Chrome and FireFoxDriver for Firefox. When you use JavascriptExecutor, Selenium sends the JS code to the browser’s JS engine for execution.
Syntax:

JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript(script, arguments);

Commands for using JavascriptExecutor in Selenium

JavascriptExecutor can be used to simulate various actions such as clicking, scrolling, getting and setting text, refreshing the page, etc.

First you need to import the JavascriptExecutor interface, create a reference to it, and then call its methods.

//import the package
import org.openqa.selenium.JavascriptExecutor;
//create a reference variable
JavascriptExecutor js = (JavascriptExecutor) driver;
//call the method
js.executeScript(script, args);

Below are some of the most common commands to handle such scenarios using JavascriptExecutor Interface.

1.To click a button:

Syntax:
js.executeScript(“document.getElementById(‘element id’).click();”); OR
js.executeScript(“arguments[0].click();”, element)

Example: js.executeScript(“document.getElementById(’submit’).click();”);

2. To scroll to an element:

Syntax:
js.executeScript(“arguments[0].scrollIntoView(true);”, element);

Example:
js.executeScript(“arguments[0].scrollIntoView(true);”, subscribe);

3. To scroll to the bottom of the page:

Syntax:
js.executeScript(“window.scrollTo(0, document.body.scrollHeight)”);

4. Scroll by specified pixels:

Syntax:
js.executeScript(“window.scrollBy(x-axis, y-axis)”);

Example:

js.executeScript(“window.scrollBy(0, 400)”);

5. To type in a text box without using sendKeys:

Syntax:
js.executeScript(“document.getElementById(‘element id’).value=’Value’;”);

Example: js.executeScript(“document.getElementById(‘email’).value=’username@xyz.com’;”);

6. To get the page title:

Syntax:
String title = js.executeScript(“return document.title;”).toString();

7. To get the domain name:

Syntax:
String domainName= js.executeScript(“return document.domain;”).toString();

8. To get the URL of a web page:

Syntax:
String url= js.executeScript(“return document.URL;”).toString();

9. To navigate to a different URL:

Syntax:
js.executeScript(“window.location = ‘page url’”);

Example:
js.executeScript(“window.location = ‘ https://testgrid.io/’”);

10. To get the innertext of the entire webpage:

Syntax:
String innerText = js.executeScript(” return document.documentElement.innerText;”).toString();

11. To get the height and width of the web page:

Syntax:
String height=js.executeScript(“return window.innerHeight;”).toString();

String width=js.executeScript(“return window.innerWidth;”).toString();

12. Generate an alert on the web page:

Syntax:
js.executeScript(“alert(‘Alert message’);”);

Example:
js.executeScript(“alert(‘This is an alert triggered by JSExecutor!’);”);

Below code will help you understand better the implementation of JavascriptExecutor through Selenium code.

Pre-requisites:

  1. Java 8 or any higher version installed on the system.
  2. Eclipse or any similar IDE installed.
  3. For a plain Java project add the required Selenium Java jars and for a Maven project add the Selenium maven dependency in the pom.xml file.

                  
                        org.seleniumhq.selenium
                                selenium-java
                                4.31.0
                  


package testcases;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class JavascriptExecutorExample {

            public static void main(String[] args) {
                            WebDriver driver;
                            driver= new ChromeDriver();
                            driver.get("https://demoqa.com/text-box");
                            WebElement fullName= driver.findElement(By.cssSelector("input#userName"));
                            WebElement email= driver.findElement(By.cssSelector("input#userEmail"));
                            WebElement cAdd= driver.findElement(By.cssSelector("textarea#currentAddress"));
                            WebElement pAdd= driver.findElement(By.cssSelector("textarea#permanentAddress"));
                            WebElement submit= driver.findElement(By.cssSelector("button#submit"));
                            JavascriptExecutor js = (JavascriptExecutor) driver;
                            js.executeScript("arguments[0].value='TestUser';", fullName);
                    js.executeScript("arguments[0].value='test@yopmail.com';", email);
                            js.executeScript("arguments[0].value='India';", cAdd);
                            js.executeScript("arguments[0].value='India';", pAdd);
                            js.executeScript("arguments[0].click();", submit);
                            driver.quit();
            }
}

In the above Selenium code, first a WebDriver instance (driver) is created for ChromeDriver(). driver instance is used to navigate to the desired URL. The locators are created for the web elements that need to be interacted with by Selenium WebDriver. And later JavascriptExecutor is used to enter values in the text fields and to click on the submit button.

Below is yet another example to understand how to scroll till the bottom of the web page, fetch the page title, domain name, URL of a web page, navigate to a different URL and generate an alert on a web page through JavascriptExecutor.

package testcases; 
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class JavaScriptExecutorExample {            

            public static void main(String[] args) {
                            WebDriver driver;
                            driver= new ChromeDriver();
                            driver.get("https://demoqa.com/text-box");                      
                            JavascriptExecutor js = (JavascriptExecutor) driver;
                            //To scroll till bottom of the web page
                            js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
                            //To get the page title
                            String title =  js.executeScript("return document.title;").toString();
                            System.out.println("Page title is: "+title);
                            //To get the domain name
                            String domainName=  js.executeScript("return document.domain;").toString();
                            System.out.println("Domain name is: "+domainName);
                            //To get the URL of a web page
                            String url=  js.executeScript("return document.URL;").toString();
                            System.out.println("URL is: "+url);
                            //To navigate to a different URL
                            js.executeScript("window.location = 'https://testgrid.io/'");
                            js.executeScript("alert('This is an alert triggered by JSExecutor!');");
            }
}

Conclusion

Selenium is a powerful tool to automate web applications, however with the help of JavascriptExecutor, you can make it more versatile. This blog is for everyone who needs to learn the implementation of the JavascriptExecutor methods that is executeScript and executeAsyncScript through which you can execute Javascript code and handle different tasks which sometimes Selenium cannot execute with only Java language.

Source: This article was originally published on TestGrid.