How to use JavaScriptExecutor in Selenium: A Complete Guide

In this hands-on tutorial you will learn what is JavaScriptExecutor, how to use JavaScriptExecutor in Selenium WebDriver, its types, syntax, and usage scenarios with programming code examples.

What is Selenium?

Selenium is an open-source web automation testing tool used to validate web applications across different browsers, such as Google Chrome, Microsoft Edge, Firefox, Safari, etc.

Selenium also supports different platforms like Windows, macOS, and Linux.

Why JavaScriptExecutor?

In certain cases, selenium drivers can fail to handle a small number of web elements, such as when opening a webpage, and if in that place an unpredicted popup window arises, that will stop the selenium driver from finding the specified elements and this will cause inaccurate results.

JavaScriptExecutor in Selenium

Here comes the usage of JavaScriptExecutor for handling these types of web elements.

What is JavaScriptExecutor

JavaScriptExecutor simply acts like a terminal that is used to implement the JavaScript code through the Selenium driver. Generally, the selenium webdriver uses locators like XPath, id, CSS selector, etc.

In case these locators failed to work, we can use JavaScriptExector. It does not need any extensions, we only need to import the package “org.openqa.selenium.JavascriptExecutor” in the script to use JavaScriptExecutor.

Types of JavaScriptExecutor

JavaScriptExecutor provides two types of methods that can handle any type of interaction using JavaScript in Selenium.

  1. ExecuteScript
  2. ExecuteAsyncScript

#1) ExecuteScript

The ExecuteScript is used only to execute JS in the subject of the presently accessed webpage in Selenium. This script runs as an unnamed function and the script can return different types of values.

#2) ExecuteAsyncScript

The ExecuteAsync Script method is used to execute the asynchronous JS in the present webpage. The major difference in the ExecuteAsync script is that the webpage continues parsing even while the Async script runs in the background, which improves the overall performance of the application.

The ExecuteAsyncScript is mostly used when the sleep function has to be performed in the browser under test.

Both methods return some value and store them in a variable.

The datatypes returned are:

  • WebElement
  • Long
  • String
  • Boolean
  • List

Get Started with JavaScriptExecutor

To use JavaScriptExecutor in Selenium, we need to follow these three steps:

#1) Import the package

First, we have to import the package.

import org.openqa.selenium.JavascriptExecutor;

#2) Create a reference

For using JavaScriptExecutor, we have to create an object for the imported package.

JavascriptExecutor obj = (JavascriptExecutor) driver;

#3) Call the JavascriptExecutor method

After we created the object for JavascriptExecutor, Now call JavaScriptExecutor method by as follows:

obj.executeScript(script, args);

Basic Syntax for JavaScriptExecutor

JavascriptExecutor obj = (JavascriptExecutor) driver;
obj.executeScript(script, args);

Some of the Scenarios for Using JSExecutor

Let’s discuss some of the scenarios we could use the JavaScriptExecutor Interface for Selenium.

#1) To click the Button

js.executeScript(“document.getElementById(‘enter element id’).click();”);

#2) To send a text without using the sendkeys() method

js.executeScript(“document.getElementByID(‘element id ’).value = ‘xyz’;”);

#3) To generate an alert pop-up window

js.executeScript(“alert(‘Welcome To Sotware testing help’);”);

#4) To get InnerText of a Webpage

string Text = js.executeScript(“return document.documentElement.innerText;”).toString();

#5) To refresh the browser window

js.executeScript(“location.reload()”)

#6) To get the Title of the webpage

String titleText = js.executeScript(“return document.title;”).toString();
System.out.println(titleText);

#7) To scroll the webpage

  • To scroll the page vertically for 500 px:
    js.executeScript(“window.scrollBy(0,500)”);
  • To scroll the page vertically till the end:
    js.executeScript(“window.scrollBy(0,document.body.scrollHeight)”);

JavaScriptExecutor in Selenium WebDriver Example

In this section, we will discuss writing the code and running a test scenario by using Java e and Selenium web driver.

Pre-requisites:

For executing the code, make sure that your system has the following:

#1) Selenium
Download Selenium’s latest stable version here.

#2) Java SDK
Download the Java Software Development Kit (JDK) from here.

#3) Eclipse IDE for Java Developers
Download the Eclipse IDE from here.

#4) Chrome Driver
Download the Chrome web driver according to your Chrome version from the site here.

Suggested Reading =>> ChromeDriver Selenium Tutorial

Example of ExecuteAsyncScript

Let’s write a simple code to illustrate an example using executeAsyncScript, where we will perform the following operations:

  • Launch the browser.
  • Open site “https://www.softwaretestinghelp.com/”.
  • The application waits for 5 sec to perform further action.

Code

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;


public class ExecuteAsyncScript{
   @Test
   public void Softwaretestinghelp(){
   System.setProperty("webdriver.chrome.driver","C:\\Users\\ADMIN\\Documents\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();

//Creating the object for JavascriptExecutor 
JavascriptExecutor obj = (JavascriptExecutor)driver;

// Maximize the browser
driver.manage().window().maximize();

// Launch Website
driver.get("https://www.softwaretestinghelp.com/");

//Declare and set the start time 
long start_time = System.currentTimeMillis();

obj.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 5000);"); 
System.out.println("Passed time: " + (System.currentTimeMillis() - start_time)); 

}
}

Code Explanation

Step1: Set the path of the Chrome web driver and instantiate the driver object.
Step2: Create the reference for the JavaScriptExecutor.
Step3: Maximize the browser.
Step4: Open the URL.
Step5: Get the starting time of the execution before the script waits for 5 seconds.
Step6: Then use the use executeAsyncScript() to wait 5 seconds.
Step7: Then, get the current time.
Step8: Subtract (current time – start time) which gives the passed time
Step9: Verify the output should display more than 5000 milliseconds.

Output

Passed time: 5256

PASSED: Softwaretestinghelp

===============================================

Default test

Tests run: 1, Failures: 0, Skips: 0

Image for output:

AsyncScript

Example of ExecuteScript

We will use the following examples in the ExecuteScript:

  • Generate an Alert window using JavaScriptExecutor.
  • Scroll Down using JavaScriptExecutor.
    • Scrolling by defining pixels.
    • Scrolling up to the bottom of the page.
  • Capture Data and Navigate to different pages using JavaScriptExecutor.

Let’s get started with the first example

Example #1: Generate Alert Window Using JavaScriptExecutor

In this example, we will navigate to the “softwaretestinghelp” website and create an alert using ExecuteScript.

Steps:

  • Launch the web browser.
  • and open the site https://www.softwaretestinghelp.com/.
  • Display alert window.

Code:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;


public class ExecuteScript{
   @Test
   public void Softwaretestinghelp(){
   System.setProperty("webdriver.chrome.driver","C:\\Users\\ADMIN\\Documents\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();

//Creating the object for JavascriptExecutor 
JavascriptExecutor obj = (JavascriptExecutor)driver;

// Maximize the browser
driver.manage().window().maximize();

// Launch Website
driver.get("https://www.softwaretestinghelp.com/");

//Generate Alert window 
obj.executeScript("alert('Welcome to Sotware Testing Help');"); 

}
}

Output:

When the code is executed successfully,

  • Successfully navigated to the “Softaretestinghelp” webpage.
  • Alert window will be displayed (see image below).

Softaretestinghelp

Example #2: Scroll Down using JavaScriptExecutor.

In this example, we will discuss scrolling through the webpages using JavaScriptExecutor in two methods

  • By defining pixels
  • Scrolling up to the bottom of the webpage

#1) Scrolling webpages by defining the pixels

In this method, we will scroll through the pages using this basic syntax:

window.scrollBy(xnum,ynum);

Parameters:

Xnum(Horizontal scrolling): It is the number required to define the pixels to scroll by, along the horizontal axis. Values greater than zero will scroll to the right side of the webpage, while values less than zero will scroll to the left side of the webpage.

Ynum(Vertical Scrolling): It is the number required to define the pixels to scroll along the vertical axis. Values greater than zero will scroll to the bottom side of the webpage, while values less than zero will scroll to the upside of the webpage.

Let’s see how to scroll the webpage vertically by 500px:

  • Open the URL “https://www.softwaretestinghelp.com/ ”.
  • Scroll the page vertically by 500px.

Syntax:

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

Code:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;


public class ExecuteScript{
  @Test
  public void Softwaretestinghelp(){
  System.setProperty("webdriver.chrome.driver","C:\\Users\\ADMIN\\Documents\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();

//Creating the object for JavascriptExecutor interface
JavascriptExecutor js = (JavascriptExecutor)driver;

// Maximize the browser
driver.manage().window().maximize();

// Launch Website
driver.get("https://www.softwaretestinghelp.com/");

// Scroll Down by 500 pixels
js.executeScript("window.scrollBy(0,500)", "");

}
}

Output:

When the code is implemented, the webpage is scrolled down by 500 pixels,

See the image below for output:

Scrolled down by 500px

#2) Scrolling webpages up to the bottom of the page:

In this example, we will discuss scrolling the web pages down to the bottom of the page.

Syntax:

js.executeScript(“window.scrollBy(0,document.body.scrollHeight)”, “”);

Let’s see how to scroll the webpage up to the bottom of the page:

  • Open the URL “https://www.softwaretestinghelp.com/ ”.
  • Scroll down the page using executeScript “window.scrollBy(0,document.body.scrollHeight)”.

Code:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;


public class ExecuteScript {
  @Test
  public void Softwaretestinghelp(){
    System.setProperty("webdriver.chrome.driver","C:\\Users\\ADMIN\\Documents\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();

//Creating the object
JavascriptExecutor js = (JavascriptExecutor)driver;

// Maximize the browser
driver.manage().window().maximize();

// Launch Website
driver.get("https://www.softwaretestinghelp.com/");

// Scroll Down till the bottom of the page
js.executeScript("window.scrollBy(0,document.body.scrollHeight)");

}
}

OUTPUT:

After executing the code, the webpage is scrolled down to the bottom of the page,

See the below image for output:

Scrolled down - javascriptexecutor in selenium

Example #3: Capture Webpage Data and Navigate to different pages.

In this example, we will

  • Launch the site “https://www.softwaretestinghelp.com/ ”.
  • Fetch details of the website such as the Domain name of the current visiting website, URL of the website and, Title name of the website. Then navigate to a different page.

Code:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;


public class ExecuteScript{
   @Test
   public void Softwaretestinghelp(){
   System.setProperty("webdriver.chrome.driver","C:\\Users\\ADMIN\\Documents\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();

//In the initial step, we have to create the object for JavascriptExecutor
JavascriptExecutor obj= (JavascriptExecutor)driver;

// Maximize the browser
driver.manage().window().maximize();

// Launch Website
driver.get("https://www.softwaretestinghelp.com/");

//Getting the Name of the website. 
String Websitename =obj.executeScript("return document.domain;").toString(); 
System.out.println("Websitename = "+Websitename);

//Getting the Title of the website
String Title = obj.executeScript("return document.title;").toString(); 
System.out.println("Title = "+Title);

//Getting the URL of the website. 
String weburl = obj.executeScript("return document.URL;").toString(); 
System.out.println("URL = "+weburl);


//move to the new webpage 
obj.executeScript("window.location = 'https://www.softwaretestinghelp.com/selenium-tutorial-1/'"); 
}
}

OUTPUT:

After the code is implemented, we will get the name of the website, Url, and the title of the current website. Then it will take you to the new site.

Websitename = www.softwaretestinghelp.com

URL = https://www.softwaretestinghelp.com/

Title = Software Testing Help – FREE IT Courses and Business Software/Services Reviews

PASSED: Softwaretestinghelp

titleoutput - javascriptexecutor in selenium

navigation

Conclusion

JavaScriptExecutor in Selenium is like a terminal that is used when Webdriver is not working as expected because some pop-up or an alert can arise on the webpage. JavaScriptExecutor allows executing JavaScript code on the web page from selenium Webdriver, enabling it to handle different types of operations by using only Java.

In this article, we learned two types: JavascriptExecutor in Selenium WebDriver and also how to use that in applications. Further, we covered various scenarios of using the JavaScriptExecutor on the webpage.

We learned the following by implementing practical examples:

  • Generate Alert window.
  • Scrolling webpages by defining pixels.
  • Scrolling webpages up to the bottom of the page.
  • Retrieved Website details using JavaScriptExecutor.
  • Navigated to different webpages using JavaScriptExecutor.