---
description: JavaScriptExecutor is an Interface that helps to execute JavaScript through Selenium Webdriver. JavaScriptExecutor provides two methods &quot;&quot;executescript&quot;&quot; &amp; &quot;&quot;executeAsyncScript&quot;&quot; to run javascript on the selected window or current page.
title: JavaScriptExecutor in Selenium WebDriver (Example)
image: https://www.guru99.com/images/javascriptexecutor-in-selenium.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

JavaScriptExecutor in Selenium WebDriver runs JavaScript inside the browser when locators fall short. Lessons cover executeScript, executeAsyncScript, scroll, click, alerts, and form input examples.

* ⚙️ **Solves Limits:** Bypasses hidden elements and JavaScript-heavy pages.
* 🧩 **Two Methods:** executeScript runs sync; executeAsyncScript handles async via callback.
* 📜 **Scroll:** Scroll window, jump to coords, or scroll an element into view.
* 🖱️ **Hidden Clicks:** Trigger click() on elements WebDriver cannot reach.
* 📝 **Form Control:** Inject values and read text from tricky elements.
* 🤖 **AI Snippets:** AI tools generate JavaScriptExecutor code and fix flaky selectors.

[ Read More ](javascript:void%280%29;) 

![JavaScriptExecutor in Selenium](https://www.guru99.com/images/javascriptexecutor-in-selenium.png)

## What is JavaScriptExecutor?

JavaScriptExecutor is an Interface that helps to execute JavaScript through Selenium Webdriver. JavaScriptExecutor provides two methods “executescript” & “executeAsyncScript” to run javascript on the selected window or current page.

[](https://www.guru99.com/images/ccna/061516%5F1127%5FExecuteJava1.png)

## Why do we need JavaScriptExecutor?

In Selenium Webdriver, locators like XPath, CSS, etc. are used to identify and perform operations on a web page.

In case, these locators do not work you can use JavaScriptExecutor. You can use JavaScriptExecutor to perform an desired operation on a web element.

Selenium supports javaScriptExecutor. There is no need for an extra plugin or add-on. You just need to import (**org.openqa.selenium.JavascriptExecutor**) in the script as to use JavaScriptExecutor.

## JavaScriptExecutor Methods in Selenium

### executeScript

This method executes [ JavaScript ](https://www.guru99.com/interactive-javascript-tutorials.html) in the context of the currently selected frame or window in Selenium. The script used in this method runs in the body of an anonymous function (a function without a name). We can also pass complicated arguments to it.

**The script can return values. Data types returned are**

* Boolean
* Long
* String
* List
* WebElement.

**JavascriptExecutor syntax:**

JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(Script,Arguments);

* **Script** – This is the JavaScript that needs to execute.
* **Arguments** – It is the arguments to the script. It’s optional.

### executeAsyncScript

With Asynchronous script, your page renders more quickly. Instead of forcing users to wait for a script to download before the page renders. This function will execute an asynchronous piece of JavaScript in the context of the currently selected frame or window in Selenium. The JS so executed is single-threaded with a various callback function which runs synchronously.

### RELATED ARTICLES

* [Verify Element Present & waitFor Command in Selenium ](https://www.guru99.com/enhancing-selenium-ide-script.html "Verify Element Present & waitFor Command in Selenium")
* [Selenium Framework: Data, Keyword & Hybrid Driven ](https://www.guru99.com/creating-keyword-hybrid-frameworks-with-selenium.html "Selenium Framework: Data, Keyword & Hybrid Driven")
* [FindElement by XPath in Selenium ](https://www.guru99.com/find-element-selenium.html "FindElement by XPath in Selenium")
* [How to Handle Proxy Authentication in Selenium Webdriver ](https://www.guru99.com/selenium-proxy-authentication.html "How to Handle Proxy Authentication in Selenium Webdriver")

## How to use JavaScriptExecutor in Selenium

Here is a step-by-step process on how to use JavaScriptExecutor in Selenium:

**Step 1)** Import the package.

import org.openqa.selenium.JavascriptExecutor;

**Step 2)** Create a Reference.

JavascriptExecutor js = (JavascriptExecutor) driver;

**Step 3)** Call the JavascriptExecutor method.

js.executeScript(script, args);

## Example of Click an Element using JavaScripExecutor in Selenium

For executeScript, we will see three different example one by one.

### 1) Example: Click a button to login and generate Alert window using JavaScriptExecutor.

In this scenario, we will use “Guru99” demo site to illustrate JavaScriptExecutor. In this example,

* Launch the web browser
* open the site <https://demo.guru99.com/V4/> and
* login with credentials

[](https://www.guru99.com/images/ccna/061516%5F1127%5FExecuteJava2.png)

* Display alert window on successful login.

import org.openqa.selenium.By;		
import org.openqa.selenium.JavascriptExecutor;		
import org.openqa.selenium.WebDriver;		
import org.openqa.selenium.WebElement;		
import org.openqa.selenium.firefox.FirefoxDriver;		
import org.testng.annotations.Test;		
    		
public class JavaSE_Test {				


    @Test		
    public void Login() 					
    {		
        WebDriver driver= new FirefoxDriver();			
        		
        //Creating the JavascriptExecutor interface object by Type casting		
        JavascriptExecutor js = (JavascriptExecutor)driver;		
        		
        //Launching the Site.		
        driver.get("https://demo.guru99.com/V4/");			
        		
        WebElement button =driver.findElement(By.name("btnLogin"));			
        		
        //Login to Guru99 		
        driver.findElement(By.name("uid")).sendKeys("mngr34926");					
        driver.findElement(By.name("password")).sendKeys("amUpenu");					
        		
        //Perform Click on LOGIN button using JavascriptExecutor		
        js.executeScript("arguments[0].click();", button);
                                
        //To generate Alert window using JavascriptExecutor. Display the alert message 			
        js.executeScript("alert('Welcome to Guru99');");   
    		
    }		
}

**Output:** When the code is executed successfully. You will observe

* Successful click on login button and the
* Alert window will be displayed (see image below).

[](https://www.guru99.com/images/ccna/061516%5F1127%5FExecuteJava3.png)

### 2) Example: Capture Scrape Data and Navigate to different pages using JavaScriptExecutor.

Execute the below selenium script. In this example,

* Launch the site
* Fetch the details of the site like URL of the site, title name and domain name of the site.
* Then navigate to a different page.

import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class JavaSE\_Test { @Test public void Login() { WebDriver driver\= new FirefoxDriver(); //Creating the JavascriptExecutor interface object by Type casting JavascriptExecutor js \= (JavascriptExecutor)driver; //Launching the Site. driver.get("https://demo.guru99.com/V4/"); //Fetching the Domain Name of the site. Tostring() change object to name. String DomainName = js.executeScript("lkw">return document.domain;").toString(); System.out.println("Domain name of the site = "+DomainName); //Fetching the URL of the site. Tostring() change object to name String url = js.executeScript("lkw">return document.URL;").toString(); System.out.println("URL of the site = "+url); //Method document.title fetch the Title name of the site. Tostring() change object to name String TitleName = js.executeScript("lkw">return document.title;").toString(); System.out.println("Title of the page = "+TitleName); //Navigate to new Page i.e to generate access page. (launch new url) js.executeScript("window.location = 'https://demo.guru99.com/'"); } } 

**Output:** When above code is executed successfully, it will fetch the details of the site and navigate to different page as shown below.

[](https://www.guru99.com/images/ccna/061516%5F1127%5FExecuteJava4.png)

[TestNG] Running:		
  C:\Users\gauravn\AppData\Local\Temp\testng-eclipse-467151014\testng-customsuite.xml		

log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).		
log4j:WARN Please initialize the log4j system properly.		
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.		
Domain name of the site = demo.guru99.com		
URL of the site = https://demo.guru99.com/V4/		
Title of the page = Guru99 Bank Home Page		
PASSED: Login		

===============================================		
    Default test		
    Tests run: 1, Failures: 0, Skips: 0
===============================================

[](https://www.guru99.com/images/ccna/061516%5F1127%5FExecuteJava5.png)

### 3) Example: Scroll Down using JavaScriptExecutor.

Execute the below selenium script. In this example,

* Launch the site
* Scroll down by 600 pixel

import org.openqa.selenium.JavascriptExecutor;		
import org.openqa.selenium.WebDriver;		
import org.openqa.selenium.firefox.FirefoxDriver;		
import org.testng.annotations.Test;		
    		
public class JavaSE_Test {				

    @Test		
    public void Login() 					
    {		
        WebDriver driver= new FirefoxDriver();			
        		
        //Creating the JavascriptExecutor interface object by Type casting		
        JavascriptExecutor js = (JavascriptExecutor)driver;		
        		
        //Launching the Site.		
        driver.get("http://moneyboats.com/");			
     
        //Maximize window		
        driver.manage().window().maximize();		
        		
        //Vertical scroll down by 600  pixels		
        js.executeScript("window.scrollBy(0,600)");			
    }		
}

**Output**: When above code is executed, it will scroll down by 600 pixels (see image below).

[](https://www.guru99.com/images/ccna/061516%5F1127%5FExecuteJava6.png)

## Example of executeAsyncScript in Selenium

Using the executeAsyncScript, helps to improve the performance of your test. It allows writing test more like a normal coding.

The execSync blocks further actions being performed by the Selenium browser but execAsync does not block action. It will send a callback to the server-side[ Testing ](https://www.guru99.com/software-testing.html)suite once the script is done. It means everything inside the script will be executed by the browser and not the server.

### RELATED ARTICLES

* [Verify Element Present & waitFor Command in Selenium ](https://www.guru99.com/enhancing-selenium-ide-script.html "Verify Element Present & waitFor Command in Selenium")
* [Selenium Framework: Data, Keyword & Hybrid Driven ](https://www.guru99.com/creating-keyword-hybrid-frameworks-with-selenium.html "Selenium Framework: Data, Keyword & Hybrid Driven")
* [FindElement by XPath in Selenium ](https://www.guru99.com/find-element-selenium.html "FindElement by XPath in Selenium")
* [How to Handle Proxy Authentication in Selenium Webdriver ](https://www.guru99.com/selenium-proxy-authentication.html "How to Handle Proxy Authentication in Selenium Webdriver")

### Example 1: Performing a sleep in the browser under test.

In this scenario, we will use “Guru99” demo site to illustrate executeAsyncScript. In this example, you will

* Launch the browser.
* Open site <https://demo.guru99.com/V4/>.
* Application waits for 5 sec to perform a further action.

**Step 1)** Capture the start time before waiting for 5 seconds ( 5000 milliseconds) by using executeAsyncScript() method.

**Step 2)** Then, use executeAsyncScript() to wait 5 seconds.

**Step 3)** Then, get the current time.

**Step 4)** Subtract (current time – start time) = passed time.

**Step 5)** Verify the output it should display more than 5000 milliseconds

import java.util.concurrent.TimeUnit;		

import org.openqa.selenium.JavascriptExecutor;		
import org.openqa.selenium.WebDriver;		
import org.openqa.selenium.firefox.FirefoxDriver;		
import org.testng.annotations.Test;		
    		
public class JavaSE_Test {				

    @Test		
    public void Login() 					
    {		
        		
        WebDriver driver= new FirefoxDriver();			

        //Creating the JavascriptExecutor interface object by Type casting		
        JavascriptExecutor js = (JavascriptExecutor)driver;		
        		
        //Launching the Site.		
        driver.get("https://demo.guru99.com/V4/");			
     
          //Maximize window		
          driver.manage().window().maximize();		
        		
          //Set the Script Timeout to 20 seconds		
          driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);			
             
          //Declare and set the start time		
          long start_time = System.currentTimeMillis();			
                   
          //Call executeAsyncScript() method to wait for 5 seconds		
          js.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 5000);");			
          		
         //Get the difference (currentTime - startTime)  of times.		
         System.out.println("Passed time: " + (System.currentTimeMillis() - start_time));					
                    		
    }		
}			

**Output:** Successfully displayed the passed time more than 5 seconds(5000 miliseconds) as shown below:

[TestNG] Running:		
C:\Users\gauravn\AppData\Local\Temp\testng-eclipse-387352559\testng-customsuite.xml		
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).		
log4j:WARN Please initialize the log4j system properly.		
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.		
Passed time: 5022		
PASSED: Login		

===============================================		
    Default test		
    Tests run: 1, Failures: 0, Skips: 0		
===============================================

## FAQs

⚡ When to use JavaScriptExecutor?

When locators fail, for hidden elements, scrolling, or DOM access WebDriver does not expose.

🤖 Can AI write JavaScriptExecutor code?

Yes. Copilot generates snippets, suggests scroll patterns, and refactors flaky tests.

💡 Does AI reduce flaky tests?

Yes. Testim and Mabl auto-heal selectors and add JavaScript fallbacks.

🧩 executeScript vs executeAsyncScript?

executeScript is sync. executeAsyncScript completes via callback for async code.

📜 How to scroll to an element?

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

🛡️ Is JavaScriptExecutor bad practice?

Use it only when WebDriver commands fail or DOM manipulation is needed.

🔒 Can it handle native alerts?

No. It can override window.alert before triggering. Use Alert API for native dialogs.

📚 How to get return values?

Cast the executeScript result, e.g. String t = (String) js.executeScript(“return document.title;”);.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/javascriptexecutor-in-selenium.png","url":"https://www.guru99.com/images/javascriptexecutor-in-selenium.png","width":"700","height":"250","caption":"JavaScriptExecutor in Selenium","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/execute-javascript-selenium-webdriver.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/selenium","name":"Selenium"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/execute-javascript-selenium-webdriver.html","name":"JavaScriptExecutor in Selenium WebDriver (Example)"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/execute-javascript-selenium-webdriver.html#webpage","url":"https://www.guru99.com/execute-javascript-selenium-webdriver.html","name":"JavaScriptExecutor in Selenium WebDriver (Example)","dateModified":"2026-06-23T16:16:07+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/javascriptexecutor-in-selenium.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/execute-javascript-selenium-webdriver.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/admin","name":"Krishna Rungta","url":"https://www.guru99.com/author/admin","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/krishna-rungta-v2-120x120.png","url":"https://www.guru99.com/images/krishna-rungta-v2-120x120.png","caption":"Krishna Rungta","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Selenium","headline":"JavaScriptExecutor in Selenium WebDriver (Example)","description":"JavaScriptExecutor is an Interface that helps to execute JavaScript through Selenium Webdriver. JavaScriptExecutor provides two methods &quot;&quot;executescript&quot;&quot; &amp; &quot;&quot;executeAsyncScript&quot;&quot; to run javascript on the selected window or current page.","keywords":"selenium","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/admin","name":"Krishna Rungta"},"dateModified":"2026-06-23T16:16:07+05:30","image":{"@id":"https://www.guru99.com/images/javascriptexecutor-in-selenium.png"},"copyrightYear":"2026","name":"JavaScriptExecutor in Selenium WebDriver (Example)","subjectOf":[{"@type":"HowTo","name":"How to use JavaScriptExecutor in Selenium","description":"Here is a step-by-step process on how to use JavaScriptExecutor in Selenium:","step":[{"@type":"HowToStep","name":"Step 1) Import the package","text":"import org.openqa.selenium.JavascriptExecutor;","url":"https://www.guru99.com/execute-javascript-selenium-webdriver.html#step1"},{"@type":"HowToStep","name":"Step 2) Create a Reference","text":"JavascriptExecutor js = (JavascriptExecutor) driver;","url":"https://www.guru99.com/execute-javascript-selenium-webdriver.html#step2"},{"@type":"HowToStep","name":"Step 3) Call the JavascriptExecutor method","text":"js.executeScript(script, args);","url":"https://www.guru99.com/execute-javascript-selenium-webdriver.html#step3"}]},{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"When to use JavaScriptExecutor?","acceptedAnswer":{"@type":"Answer","text":"When locators fail, for hidden elements, scrolling, or DOM access WebDriver does not expose."}},{"@type":"Question","name":"Can AI write JavaScriptExecutor code?","acceptedAnswer":{"@type":"Answer","text":"Yes. Copilot generates snippets, suggests scroll patterns, and refactors flaky tests."}},{"@type":"Question","name":"Does AI reduce flaky tests?","acceptedAnswer":{"@type":"Answer","text":"Yes. Testim and Mabl auto-heal selectors and add JavaScript fallbacks."}},{"@type":"Question","name":"executeScript vs executeAsyncScript?","acceptedAnswer":{"@type":"Answer","text":"executeScript is sync. executeAsyncScript completes via callback for async code."}},{"@type":"Question","name":"How to scroll to an element?","acceptedAnswer":{"@type":"Answer","text":"Call js.executeScript(\"arguments[0].scrollIntoView(true);\", element)."}},{"@type":"Question","name":"Is JavaScriptExecutor bad practice?","acceptedAnswer":{"@type":"Answer","text":"Use it only when WebDriver commands fail or DOM manipulation is needed."}},{"@type":"Question","name":"Can it handle native alerts?","acceptedAnswer":{"@type":"Answer","text":"No. It can override window.alert before triggering. Use Alert API for native dialogs."}},{"@type":"Question","name":"How to get return values?","acceptedAnswer":{"@type":"Answer","text":"Cast the executeScript result, e.g. String t = (String) js.executeScript(\"return document.title;\");."}}]}],"@id":"https://www.guru99.com/execute-javascript-selenium-webdriver.html#schema-248857","isPartOf":{"@id":"https://www.guru99.com/execute-javascript-selenium-webdriver.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/execute-javascript-selenium-webdriver.html#webpage"}}]}
```
