Open In App

JavaScriptExecutor in Selenium

Last Updated : 29 Jul, 2025
Comments
Improve
Suggest changes
24 Likes
Like
Report

The JavaScriptExecutor is an interface in Selenium that enables you to execute JavaScript code within the context of the current page loaded in the browser. When a user opens a website, an unexpected pop-up window may appear, preventing the WebDriver from performing operations and producing inaccurate results. This is where the JavaScriptExecutor comes into use.

JavaScriptExecutor provides two methods:

1. ExecuteScript

This method executes JavaScript in the currently selected window or frame. The script runs as an anonymous function, and the script can return values. Data types returned are :

  • WebElement
  • List
  • String
  • Long
  • Boolean

2. ExecuteAsyncScript

This method is used to execute the asynchronous JavaScript in the current window or frame. An asynchronous JavaScript execution is a single thread, while the rest of the page continues parsing. which enhances the performance.

JavaScriptExecutor Use Cases

Here are a few more use cases of the JavaScript Executor in Selenium:

1. To refresh the Browser Window

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("location.reload()");

2. Send Text to an Element

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('elementId').value = 'text';");

3. Generate an Alert Popup

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("alert('Hello World');");

4. Get Inner Text of a WebPage

JavascriptExecutor js = (JavascriptExecutor) driver;
String text = js.executeScript("return document.documentElement.innerText;").toString();
System.out.println(text);

5. Get Title of a WebPage

JavascriptExecutor js = (JavascriptExecutor) driver;
String title = js.executeScript("return document.title;").toString();
System.out.println(title);

6. Scroll the Page

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0, 150);"); // Vertical scroll by 150 pixels

How to Use JavaScriptExecutor in Selenium

1. Import the package

Import org.openqa.selenium.JavascriptExecutor;

2. Create a reference

JavascriptExecutor js = (JavascriptExecutor) driver;

3. Call the JavascriptExecutor method

js.executeScript(script, args);

We will use JavaScriptExecutor to enter text into a search field on the GeeksforGeeks website.

JsEnterText.java

Java
package pages;

import java.time.Duration;

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;
import org.openqa.selenium.support.ui.WebDriverWait;

public class JsEnterText {
    public static void main(String[] args) {
        try {
            // Set the path to the ChromeDriver executable (replace with your path)
            System.setProperty("webdriver.chrome.driver", "C:\\Users\\path of the chrome-web-driver\\drivers\\chromedriver.exe");

            // Initialize the ChromeDriver
            WebDriver driver = new ChromeDriver();
            
            // Launch the URL
            driver.get("https://www.geeksforgeeks.org/");
            
            // Add a sleep to slow down for visual observation
            Thread.sleep(2000); // Wait for 2 seconds

            // Explicit wait
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
        
            // JavaScript Executor to enter text
            JavascriptExecutor js = (JavascriptExecutor) driver;
            WebElement textBox = driver.findElement(By.className("HomePageSearchContainer_homePageSearchContainer_container_input__1LS0r"));

            // Add sleep before entering text
            Thread.sleep(2000); // Wait for 2 seconds

            // Enter text using JavaScript
            js.executeScript("arguments[0].value='Selenium';", textBox);
            
            // Add sleep after entering text to observe the result
            Thread.sleep(2000); // Wait for 2 seconds
            
            // Verify value
            String value = textBox.getAttribute("value");
            System.out.println("Value entered is: " + value);
            
            // Add sleep before quitting
            Thread.sleep(2000); // Wait for 2 seconds

            // Cleanup
            driver.quit();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output:

Output-of-Js-executor
Output of JS Executor

We use JavaScriptExecutor in Selenium to perform advanced actions such as clicking elements, entering text, and interacting with the page in ways that traditional WebDriver methods might struggle with there JavaScriptExecutor will be used.


Explore