Testing With Selenium WebDriver (73 Blogs) Become a Certified Professional
AWS Global Infrastructure

Software Testing

Topics Covered
  • Testing With Selenium WebDriver (63 Blogs)
SEE MORE

Practical Guide to Using JavascriptExecutor in Selenium

Published on Jun 06,2024 44 Views

A passionate and knowledgeable tech enthusiast known for his expertise in the... A passionate and knowledgeable tech enthusiast known for his expertise in the world of technology and programming. With a deep-rooted passion for coding, Sarfaraz...

Selenium is a well-known open-source web-based automation tool. It is commonly used for web-based automation testing. In a survey, 59.5% of testers want Selenium to manage their browsers for them. However, the Selenium WebDriver may not always be helpful for all web elements. In such cases, the JavasciptExecutor is used to locate specific elements to generate accurate outputs. In this blog, let’s learn about JavascriptExecutor in Selenium and its uses.

What is JavascriptExecutor in Selenium?

Simply put, the JavascriptExceutor is an interface that bridges the gap between Selenium WebDriver and JavaScript. It allows the execution of JavaScript code within the current browser frame. There is no need to download any extra plug-in or add-on to start using JavaScriptExecutor.

When the built-in WebDriver methods don’t offer the necessary functionality, you can use the JavascriptExceutor. It can interact with the HTML DOM of the webpage.

When the built-in WebDriver can access HTML elements, there is no need to use the JavaScript Executor. Now that we know how to use the JavaScript Executor, it is essential to understand when and why it must be used.

Want to learn more about Selenium? Have a look at this industry expert-curated Selenium Course today.

Why do we need JavaScriptExecutor?

JS executor in Selenium is important when you have issues using the built-in methods. Certain conditions may not be easy to handle with Webdriver, or sometimes, the web controls don’t interact as expected. In such cases, the use of JavaScript Executor in Selenium becomes important. It is widely used in the following circumstances:

  • Overcoming Locator Limitations – When the standard Selenium locators – ID, XPath, and CSS selectors fail to locate elements due to overlapping elements, dynamic content, or complex web page structures, JavaScriptExecutor can be used as an alternative approach.
  • Dynamic Interactions – Certain JavaScript-specific actions like clicking hidden elements, handling dynamic elements, or working with elements not part of the HTML DOM packages can be used with the JavaScriptExecutor in Selenium.
  • Advanced DOM Manipulation – Compared to the built-in Webdriver methods, advanced DOM manipulation tasks can be performed using JavaScriptExecutor.

Remember to import JavaScriptExecutor using org.openqa.selenium.JavascriptExecutor to test scripts. Using the right JavaScriptExecutor component depends on the context in which test scripts are used.

Components of JavascriptExecutor in Selenium

The two main components of JavaScriptExecutor in Selenium are:

1. executeScript

  • Executes JavaScript synchronously within the context of the selected window or frame in Selenium.
  • Runs in the body of an anonymous function without a name.
  • It can accept arguments.
  • It returns values of different data types like Boolean, long, string, list, and WebElement.

2. executeAsyncScript

  • Executes JavaScript asynchronously, allowing the script to run in the background without blocking the test execution.
  • It allows the page to render more quickly as the users don’t have to wait for the script to download.
  • It requires a callback function to handle the result of the asynchronous operation once it is finished.

Depending on how the script must be allowed to run or tested, the component used is chosen. In the next section, let’s understand how to use JavaScriptExecutor in several use cases.

How to get started with JavascriptExecutor?

To start using JavascriptExecutor, follow the steps below:

Step 1: Import the package

import org.openqa. Selenium.JavascriptExecutor;

Step 2: Create a Webdriver instance

WebDriver driver = new ChromeDriver(); // Or your preferred browser driver

Step 3: Cast the web driver to JavascriptExecutor

CJavascriptExecutor js = (JavascriptExecutor) driver;

Step 4: Call the JavascriptExecutor method

js.executeScript(script, args);

How JavascriptExecutor works in Selenium?

When you use JavascriptExecutor in Selenium, as stated above, it works in the following way:

  • Using the executeScript method, you provide the JavaScript code.
  • Selenium takes this code and converts it into a WebDriver command.
  • This command is forwarded to the browser.
  • The browser takes over to execute the JavaScript code within the context.
  • The output of the JavaScript code is returned to the Selenium. If the code doesn’t generate any output, Selenium will not receive any output.

JS Executor in Selenium is commonly used in several cases. It is helpful for simulating user interactions with HTML elements in test scripts.

Why use JavascriptExecutor in Selenium?

The limitations of Selenium standard methods are overcome with the use of JavascriptExecutor. Dynamic content is handled only using the JS executor. Also, when greater DOM manipulation is needed, the built-in webdriver methods cannot be used. Some of the common actions performed using JavascriptExecutor in Selenium are:

  • Scrolling to an element that is not immediately visible on the screen or one that is located below the fold.
  • Capturing contents of a page to verify or validate certain elements or text on a page.
  • Moving the mouse over a web element.
  • Opening a pop-up window
  • Highlighting an element on the web page.

Use Case Scenarios

Let’s understand the use of JavascriptExecutor in Selenium with some common examples.

#1 Login to a website and generate an alert window

import org.openqa. Selenium.By;

import org.openqa. Selenium.JavascriptExecutor;

import org.openqa. Selenium.WebDriver;

import org.openqa. Selenium.chrome.ChromeDriver;

import org.openqa. Selenium.Alert;

public class LoginAutomationWithJavascript {

public static void main(String[] args) {

// Replace with your actual website URL and login credentials

String websiteUrl = "https://www.example.com/login";

String username = "your_username";

String password = "your_password";

// Initialize WebDriver

System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); // Replace with your ChromeDriver path

WebDriver driver = new ChromeDriver();

// Open the login page

driver.get(websiteUrl);

// Locate username and password fields

WebElement usernameField = driver.findElement(By.id("username"));

WebElement passwordField = driver.findElement(By.id("password"));

// Enter username and password

usernameField.sendKeys(username);

passwordField.sendKeys(password);

// Cast WebDriver to JavascriptExecutor

JavascriptExecutor js = (JavascriptExecutor) driver;

// Login using JavaScript (simulating button click)

js.executeScript("arguments[0].click();", driver.findElement(By.id("login_button")));

// Generate an alert after login using JavaScript

String alertMessage = "Login successful!";

js.executeScript("alert('" + alertMessage + "');");

// Switch to the alert window and accept it

Alert alert = driver.switchTo().alert();

alert.accept();

// Close the browser

driver.quit();

}

}

Output – The script will launch your chosen browser, Chrome and navigate to the login page URL. It will locate the username and password fields on the login page and enter the given credentials into them. Using JavascriptExecutor, the login button click is simulated without direct user interaction. Then, the alert window with the message Login Successful will be created.

# 2 Use the executeAsyncScript method to scroll down to the bottom of a webpage.

import org.openqa. Selenium.By;

import org.openqa. Selenium.JavascriptExecutor;

import org.openqa. Selenium.WebDriver;

import org.openqa. Selenium.chrome.ChromeDriver;

public class ScrollToBottomWithJavascript {

public static void main(String[] args) {

// Replace with your actual website URL

String websiteUrl = "https://www.example.com/long-page";

// Initialize WebDriver

System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

WebDriver driver = new ChromeDriver();

// Open the webpage

driver.get(websiteUrl);

// Cast WebDriver to JavascriptExecutor

JavascriptExecutor js = (JavascriptExecutor) driver;

// Scroll down to the bottom of the page asynchronously

js.executeAsyncScript("arguments[0].scrollTo(0, document.body.scrollHeight);");

// Wait for the scrolling to finish (optional)

try {

Thread.sleep(2000); // Adjust the sleep time as needed

} catch (InterruptedException e) {

e.printStackTrace();

}

// Continue with your automation steps here...

// Close the browser

driver.quit();

}

}

Output – The script will open the Chrome browser and navigate to the given website. It smoothly scrolls down to the bottom of the page. The time taken depends on the length of the page. With the sleep method, the script will pause for 2 seconds after scrolling to load the page content fully.

#3 Retrieving the title of a web page

import org.openqa. Selenium.By;

import org.openqa. Selenium.JavascriptExecutor;

import org.openqa. Selenium.WebDriver;

import org.openqa. Selenium.chrome.ChromeDriver;

public class GetPageTitleWithJavascript {

public static void main(String[] args) {

// Replace with your actual website URL

String websiteUrl = "https://www.example.com";

// Initialize WebDriver

System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");

WebDriver driver = new ChromeDriver();

// Open the webpage

driver.get(websiteUrl);

// Cast WebDriver to JavascriptExecutor

JavascriptExecutor js = (JavascriptExecutor) driver;

// Get the webpage title using JavaScript

String pageTitle = (String) js.executeScript("return document.title;");

// Print the page title

System.out.println("Page Title: " + pageTitle);

// Close the browser

driver.quit();

}

}

Output – The script will launch a Chrome browser and open the given URL. The title will be retrieved and shown as Page Title: <retrieved webpage title>

Conclusion

Selenium encounters many issues for web browser testing automation due to the limitations of the Webdriver method. The JavascriptExecutor in Selenium allows for interactions with multiple web elements using the executeScript and executeAsyncScript methods. As there is no need for additional plug-ins, using the JS executor in Selenium is a straightforward process.

FAQs

What are the prerequisites to execute the example codes using Java and Selenium?

To execute the example codes mentioned above, you need to download Selenium, Java SDK, Eclipse IDE, and Chrome driver.

What are the benefits of using JavascriptExecutor in Selenium?

It allows you to interact with different types of web elements that are not possible with the webdriver methods. Dynamic web pages are handled more efficiently with JavascriptExecutor.

Are there any drawbacks to using JavascriptExecutor in Selenium?

Overreliance on JavaScript can result in automation scripts that are dependent on browser implementations. Compared to standard Selenium methods, debugging of Javascript used in automation scripts can be cumbersome for complex activities.

When should I not use JavascriptExecutor?

If the standard Selenium locators and methods can effectively locate and interact with the required web elements, don’t use JavascriptExecutor. Simple interactions on well-structured web pages don’t require a JS executor.

Which programming languages can I use for JavascriptExecutor in Selenium?

JavascriptExecutor in Selenium can be used with programming languages supported by Selenium, such as Java, C#, Python, and JavaScript. Regardless of the language used for binding the interface with Selenium Webdriver, the JavascriptExecutor runs in the same manner.

Upcoming Batches For Selenium Certification Training Course
Course NameDateDetails
Selenium Certification Training Course

Class Starts on 24th June,2024

24th June

MON-FRI (Weekday Batch)
View Details
Selenium Certification Training Course

Class Starts on 29th June,2024

29th June

SAT&SUN (Weekend Batch)
View Details
Selenium Certification Training Course

Class Starts on 15th July,2024

15th July

MON-FRI (Weekday Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Practical Guide to Using JavascriptExecutor in Selenium

edureka.co