What is JavaScriptExecutor in Selenium?

We have already seen many tutorials that tackle different elements actions and scenarios.  But sometimes Selenium web driver has problems interacting with certain web elements, like when a user opens a website and there is an unexpected pop-up window that prevents the web driver from doing things and makes the results inaccurate. JavascriptExecutor comes to the rescue, in this case.

What is JavaScriptExecutor in Selenium?

The JavaScriptExecutor interface is used to execute JavaScript through Selenium WebDriver. JavaScript is a programming language that works with HTML in a browser. To use this function in Selenium, you need JavascriptExecutor.

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. JavascriptExecutor can be used to perform an operation on the 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 Provides Two Methods:

  1. ExecuteScript
  2. ExecuteAsyncScript

1. ExecuteScript

This method runs JavaScript in the current window or frame. The script can return values when it runs as an anonymous function. Data types returned are :

    1. For an HTML element, the method returns a WebElement.
    2. For a decimal, the method returns Long.
    3. For a non-decimal number, the method returns Long.
    4. For a Boolean, the method returns Boolean.
    5. For other cases, the method returns a String.

2. ExecuteAsyncScript

This method is used to execute the asynchronous JavaScript in the current window or frame. An asynchronous JavaScript task runs on a single thread, while the rest of the page continues parsing. Which improves performance.


Considering the issues that Selenium sometimes faces when interacting with web elements, it is imperative for Selenium testers to learn how to use JavascriptExecutor methods. The implementation of both methods is a perfect solution for any potential issues.

Similar Posts