How To Use JavaScriptExecutor in Selenium WebDriver?

Harita Ravindranath

Posted On: May 3, 2021

view count104261 Views

Read time10 Min Read

Webdriver is a tool that requires no introduction in the test automation domain. Webdriver is an open-source collection of APIs which is used for testing web applications across different browsers and platforms to verify whether it is working as expected or not. The latest version of Selenium – Selenium 4 is W3C compliant – however it is still in the Beta phase (i.e. 4.0.0-beta-3).

In Selenium 3, the JSON Wire Protocol is used for communicating with the web browser from the local end. In Selenium test automation with the Selenium 3 framework, API encoding & decoding is involved in the entire process since web browsers use the W3C protocol and the Selenium Client Libraries use the JSON Wire Protocol.

Selenium 3 Architecture

Selenium WebDriver allows you to communicate with various browsers to perform commands and assertions on DOM elements using which you can perform any kind of operations like sending the text, click on a button, select a radio button, select the drop-downs, etc.

However, there are scenarios where the actual Webdriver commands will not work efficiently as expected. This is where JavaScriptExecutor comes into the picture.

In this article, we will be discussing JavaScriptExecutor in Selenium WebDriver. Also I will cover everything you need to know about how to use JavaScriptExecutor in Selenium. Getting started with an overview, we will further dive into the implementation and explore different methods in JavascriptExecutor along with working examples.

Starting your journey with Selenium WebDriver? Check out this step-by-step guide to perform Automation testing using Selenium WebDriver.

Let’s get started!

This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium JavaScript Tutorial.

What is JavaScriptExecutor in Selenium?

JavaScriptExecutor is an interface provided by Selenium Webdriver, which presents a way to execute JavaScript from Webdriver. This interface provides methods to run JavaScript on the selected window or the current page. JavaScriptExecutor is an interface which is available for all the languages that support the Selenium uses.

As JavaScriptExecutor is a Selenium interface, there is no need for an extra plugin or add-on. You can use it directly by importing the package org.openqa.selenium.JavascriptExecutor.

Why use JavaScriptExecutor in Selenium?

Selenium Webdriver alone lets you perform operations on web elements like sending data, clicking buttons, etc. However, as said before, there are scenarios where the Webdriver commands will not work as expected due to various reasons. In these cases, we take the help of JavaScriptExecutor.

For example, traditionally to locate a web element we use different web locator strategies such as ID, Name, CSS selector, and XPath, etc. If these locators do not work as expected, or you are handling a tricky XPath, you can use JavaScriptExecutor to perform the desired operation on the WebElement..

On similar lines, to click on a WebElement, we generally use the click() method provided by Selenium Webdriver.

You can check out our Learning Hub in case you want to deep dive into the various aspects of Selenium Locators. At times, 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 interface should be used.

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

Read – Test Automation With Selenium Click Button Method (Examples)

Introduction to JavaScriptExecutor Methods

JavaScriptExecutor in Selenium provides two methods through which we can run JavaScript on the selected window or the current page.

a) 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.

b) executeAsyncScript

This method executes an asynchronous snippet of JavaScript in the context of the currently selected window or frame in Selenium. Here also, the script will be executed as the body of an anonymous function. The major difference between executeScript and executeAsyncScript 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.

Both the methods allow us to return a value using the ‘return’ keyword and store them in a variable. The data types that can be returned are:

  • Long
  • String
  • Boolean
  • List
  • WebElement

You can take this certification as proof of expertise in the field of test automation with JavaScript to empower yourself and boost your career.

Here’s a short glimpse of the Selenium JavaScript 101 certification from LambdaTest:

Basic Syntax of JavaScriptExecutor in Selenium

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

Let’s take a look at the key steps.

Step 1: Import the package associated with JavascriptExecutor.

Step 2: Now to utilize JavascriptExecutor, create a reference for the interface and assign it to the WebDriver instance by type casting it.

Step 3: We have created a JavascriptExecutor reference. Now we call the executeAsyncScript/executeScript methods. The syntax for executeScript is given below:

Parameters:

script – The JavaScript to execute
args – The arguments to the script. May be empty.

Returns Value

Boolean/Long/Double/String/List/Map/WebElement/Null.

Now that we have covered the essentials of JavaScriptExecutor in Selenium, it’s time to get our hands dirty with some implementation! In the upcoming sections, we will check out some scenarios where we use JavaScriptExecutor in Selenium to perform test scenarios (that might not have been performed with common Selenium WebDriver commands).

Scenarios To Use JavaScriptExecutor in Selenium

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

1. To Click on a Button

2. To Type Text in a Text Box without using sendKeys() method

3. To Handle Checkbox by passing the value as true or false

4. To generate Alert Pop window in Selenium Webdriver

5. To refresh browser window using Javascript

6. To get the innertext of the entire webpage in Selenium

7. To get the Title of our webpage

8. To get the domain name

9. To get the URL of a webpage

10. To get the Height and Width of a web page

11. To find a hidden element in selenium using JavaScriptExecutor

12. To navigate to a different page using Javascript

13. To perform Scroll on an application using Selenium

a) To scroll the page vertically for 500px

b) To scroll the page vertically till the end

14. Adding an element in DOM

We can also add an element in DOM if required. However, as are only concerned with mimicking user interactions in the browser, this option may not be used.

On similar lines, we can practically execute any JavaScript command using Selenium.

JavaScriptExecutor in Selenium WebDriver Example

In the previous section, we looked at a widely-used JavaScriptExecutor in Selenium commands. Now it’s time to run an end-to-end test scenario! We will be continuing to use Java as the programming language for the demonstration JavaScript in Selenium WebDriver. Let’s dive in!

Pre-requisites

First and foremost, make sure that your system is equipped with the following:

1. Java SDK

Download and install the Java Software Development Kit (JDK) from here.

2. Eclipse or any IDE of choice.

Download the latest version of “Eclipse IDE for Java Developers” from here.

3. Selenium-Java client Driver

Download Selenium Webdriver for Java Client Driver from here.

4. Browser Drivers (only for Local Selenium Grid)

Download various browser drivers from here

Once this criterion is checked, proceed to create a ‘New Project’ in Eclipse. Don’t forget to configure the IDE with Webdriver by adding all the Jars required to the project.

Instead of the local Selenium Grid, the tests are run on a cloud based Selenium Grid by LambdaTest. It provides improved scalability, reliability, and better browser coverage since parallel tests can be run on a range of browser & OS combinations. LambdaTest Selenium Automation Grid is a cloud-based, scalable Selenium test automation platform that enables you to run your automation scripts on 3000+ different browsers and operating systems online.

You can effortlessly migrate the Selenium tests running on a local Selenium Grid to the LambdaTest Selenium Grid through a few additional configurations. After creating a LambdaTest account, make a note of the username & access-key available in the LambdaTest profile section. The browser capabilities are generated using LambdaTest Capabilities Generator.

Time to get our hands dirty with some implementation!

Test Scenario 1 (Demonstration of executeScript)

Login and generate an Alert window using JavaScriptExecutor

Our objective is to write a simple code to illustrate an example using executeScript, where we will:

  • Launch the web browser (Chrome – latest version on Windows 10 platform)
  • Go to URL “https://opensource-demo.orangehrmlive.com/
  • Enter dummy credentials
  • Click the login button
  • Print page title and domain name
  • Display alert window on successful login.

Run the script. The test gets executed successfully!

Observe the console output and output from Automation Dashboard on LambdaTest.

Test Scenario 2 (Demonstration of executeAsyncScript)

Login and generate an Alert window using JavaScriptExecutor

Our objective is to write a simple code to illustrate an example using executeAsyncScript, where we will:

  • Launch the web browser (Chrome – latest version on Windows 10 platform)
  • Go to URL “ https://www.lambdatest.com/
  • Wait for 10 seconds to perform a further action

Run the script. The test gets executed successfully! Here is the snapshot of the execution window (of the IDE) and automation dashboard on LambdaTest.

With this, we have successfully run our test cases on remote Selenium Grid provided by LambdaTest through a hassle-free experience!

Wrapping It Up!

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 learnt how to use JavascriptExecutor in Selenium WebDriver and also understood the different methods provided by JavascriptExecutor. Further we covered various scenarios to attain an effective solution using different methods along with practical examples.

Additionally, we have also performed Selenium test automation by adopting a remote Selenium Grid. If you wish to test and optimize the web application by unlocking coverage in a wider variety of platforms or browsers or versions, feel free to explore the LambdaTest platform.

Happy Testing!

Author Profile Author Profile Author Profile

Author’s Profile

Harita Ravindranath

A seasoned Quality Engineer with enthusiasm in Full Stack Development. Harita also enjoys reading, blogging and learning Japanese.

Blogs: 17



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free