How to Use JavaScriptExecutor in Selenium

Selenium is an open-source suite of tools and libraries that allows you to interact with browsers to perform various operations like sending text, clicking on a button, selecting drop-downs, etc.

However, there are scenarios where the actual Selenium WebDriver commands do not work as expected, as Selenium can’t interact with the WebElements directly. This is where JavaScriptExecutor comes into the picture.

In this blog, we discuss JavaScriptExecutor in Selenium and how to get started with practical use cases and examples.

What Is JavaScriptExecutor in Selenium?

JavaScriptExecutor is an interface provided by Selenium that helps in executing JavaScript commands. This interface provides methods to run JavaScript on the selected window or the current web page. It is available for all the language bindings supported by Selenium.

The JavaScriptExecutor in Selenium can be used directly by importing the following package in the automation test scripts:

Java

 

JavaScriptExecutor in Selenium provides two methods to interact with the WebElements:

  • executeScript() – This method executes JavaScript in the context of the currently selected window or frame in Selenium. The script will be executed as the body of an anonymous function.
  • executeAsyncScript()  This method executes an asynchronous snippet of JavaScript in the context of the currently selected window or frame in Selenium. The script will be executed as the body of an anonymous function.

Note: The major difference between executeScript() and executeAsyncScript() methods is that the script invoked using the executeAsyncScript() has to signal about the completion of execution using the callback() function.

Invoking methods using executeAsyncScript() are majorly used when sleep has to be performed in the browser under test or when tests have to be synchronized within an AJAX application.

Why Use JavaScriptExecutor in Selenium?

There are scenarios where some WebDriver commands do not work as expected due to multiple reasons, as follows:

  1. Selenium not interacting with the WebElements directly
  2. Performing actions like scrolling into view, clicking on the WebElements that are hidden behind the overlay, or setting values in the readonly fields
  3. Performing browser-specific behaviours like modifying the DOM dynamically

In these cases, we take the help of JavaScriptExecutor in Selenium.

Traditionally, we use Selenium locators such as ID, Name, CSS Selector, XPath, etc., to locate a WebElement. If these locators do not work, or you are handling a tricky XPath, in such cases, JavaScriptExecutor helps to locate the desired WebElement.

There are cases where the click() method may not work on all the web browsers, or the web controls might behave differently on different browsers. To overcome such situations, the JavaScriptExecutor should be used to perform a click action.

As we know, browsers have JavaScript implementation inside them and can understand JavaScript commands. Hence, understanding JavaScriptExecutor in Selenium will enable us to perform a range of operations more efficiently.

Basics of JavaScriptExecutor in Selenium

The purpose of this section is to provide a high-level idea about the implementation steps of the JavaScriptExecutor in Selenium. For the demonstration, we will be using Java as the preferred programming language.

Let’s take a look at the key steps.

1. Import the package associated with JavaScriptExecutor:

Java

 

2. Use JavaScriptExecutor, create a reference for the interface, and assign it to the WebDriver instance by type-casting it:

Java

 

3. Call the executeAsyncScript() or executeScript() methods. For example, the syntax for executeScript() is given below:

Java

 

Demo: Using JavaScriptExecutor in Selenium

Before we look at how to use JavaScriptExecuter in Selenium, follow these prerequisites:

  • Create a new Maven project using IntelliJ IDE
  • Add latest Selenium WebDriver dependency in the pom.xml
  • Add latest TestNG dependency in pom.xml

We would be using the LambdaTest eCommerce Playground website to demo the working of the JavaScriptExecutor in Selenium by running the tests on the Local Chrome browser.

Test Scenario 1

Our objective is to write a simple code to illustrate an example using the executeScript() method using the following test scenario.

  1. Navigate to the Account Login page of the LambdaTest eCommerce Playground website.
  2. Enter valid login credentials and click on the Login button by highlighting the field with a red border.
  3. Print the page title and domain name.
  4. Assert that the page header “My Account” is displayed on a successful login.

Implementation

Create a new TestJavaScriptExecutor class for implementing the test scenario. We would first create two methods in this test class that would allow us to set up and gracefully quit the Selenium WebDriver sessions.

Let’s declare the WebDriver at class level as we would need it in both of the methods, i.e, setup() method, to start the driver session and the tearDown() method, to gracefully quit the session.

Java

 

Let’s create a new setup() method that will instantiate an instance of the WebDriver class and accordingly set the configuration for running the tests on the local Chrome browser.

Java

 

This method will open the Chrome browser, maximize its window, and also apply an implicit wait of 30 seconds. This implicit wait will allow all the website contents to get loaded successfully before the test execution starts.

Available on GitHub


Java

 

Finally, when the test is executed, the tearDown() method will be called, which will close the RemoteWebDriver session gracefully.

Let’s now add a testJavaScriptExecutorCommand() method in the same test class to implement the test scenario we discussed.

Java

 

The code navigates to the Login page of the LambdaTest eCommerce Playground website. The next line casts the WebDriver instance to JavascriptExecutor so that JavaScript commands can be executed in the browser.

Java

 

Next, it locates the emailAddressField using the id locator strategy. Then, it uses the JavaScriptExecutor command to highlight the border of the e-mail address field in red color.

Java

 

Next, the password field is located and highlighted with a red border. This highlight helps in knowing what steps are getting executed at the time of automation test execution.

Java

 

Likewise, the Login button is located using the CSS Selector strategy and is highlighted as well.

Java

 

The page title and domain name are located next using the JavaScriptExecutor and printed on the console.

Java

 

Finally, the page header of the My Account page, which is displayed after a successful login, is located, and an assertion is performed to check that it displays the text “My Account.”

Here is the full code from the TestJavaScriptExecutor class:

Java

 

Test Execution

The following screenshot from the IntelliJ IDE shows that the test was executed successfully.

Test was executed successfully

Test Scenario 2

Our objective is to write a simple code to illustrate an example using the executeAsyncScript() method using the following test scenario.

  1. Navigate to the LambdaTest eCommerce Playground website.
  2. Scroll down to the bottom of the home page.
  3. Assert that the text “FROM THE BLOG” is displayed in the lower section of the page.

Implementation:

Create a new testExecuteAsyncScript() method in the existing text class TestJavaScriptExecutor.

Java

 

The code will navigate to the homepage of the LambdaTest eCommerce Playground website. The executeAsyncScript() method of the JavaScriptExecutor will be called next, where it will perform the action to scroll the window.

In the executeAsyncScript() method, the scripts executed need to explicitly signal that they are finished by invoking the provided callback() method.

Java

 

After scrolling to the bottom of the window, the text “FROM THE BLOG” will be located, and an assertion will be performed on it.

Java

 

Test Execution

The following screenshot shows that the test was executed successfully.

Test was executed successfully

Commands for Using JavaScriptExecutor in Selenium

Let’s examine some scenarios we could handle using JavaScriptExecutor Interface for Selenium test automation.

To click on a button:

Java

 

To type text in a text box without using the sendKeys() method:

Java

 

To handle the checkbox by passing the value as true or false:

Java

 

To generate an alert pop window in Selenium WebDriver:

Java

 

To refresh the browser window using JavaScript:

Java

 

To get the innertext of the entire webpage in Selenium:

Java

 

To get the title of the web page:

Java

 

To get the domain name:

Java

 

To get the URL of a web page:

Java

 

To get the height and width of a web page:

Java

 

To navigate to a different page using JavaScript:

Java

 

To perform scroll on an application using Selenium:

  • To scroll the page vertically for 500px:
    Java

     

  • To scroll the page vertically till the end:
    Java

     

Adding an element in the Document Object Model (DOM):

Java

 

To get the shadow root in the DOM:

Java

 

Conclusion

Selenium has an interface called JavaScriptExecutor that is utilized when WebDriver commands don’t behave as intended. With the help of JavaScriptExecutor, we can use WebDriver to execute JavaScript code on the website, allowing us to handle a variety of tasks in an elegant and effective manner that would otherwise be impossible using only Java.

In this blog, we explored how to use JavaScriptExecutor in Selenium and its different methods. Further, we covered various scenarios to attain an effective solution using different methods along with practical examples.

Source:
https://dzone.com/articles/how-to-use-javascriptexecutor-in-selenium