JavascriptExecutor in Selenium


Selenium is a well-known open source, web-based automation tool used by many. But sometimes it faces problems when interacting with certain elements; perhaps an unexpected pop-up window will hinder the web-driver from performing operations and generate wrong results. This is where JavascriptExecutor proves to be a key factor in such a situation, enabling the web driver to successfully perform the desired operations. Its complexity and bursts, working side by side, make this situation much easier to tackle.

What is JavascriptExecutor in Selenium?

Using the interface named JavascriptExecutor one can execute JavaScript via Selenium and to interact with HTML within a browser while using this programming language it is mandatory that you utilize the JavascriptExecutor object, creating sentence structures that vary in length and complexity is crucial for composing an intriguing text. As such the JavaScript Executor grants means for communicating with HTML inside a web-browser along with facilitating programmers to fashion cleverly dexterous expressions using their own unique styles of writing in JavaScript.

Methods

Following are the methods offered by JavascriptExecutor in Selenium −

ExecuteScript

Executing JavaScript in the presently chosen window or frame has never been so easy! By calling an anonymous function, this method enables users to reap the rewards of a multitude of data types, including −

  • Web Elements

  • Lists

  • Strings

  • Long

  • Boolean

  • ExecuteAsyncScript

Asynchronous JavaScript execution is a multi-threaded approach to execute individual JavaScript tasks in the current window or frame. It allows page parsing to continue, optimizing performance and providing great flexibility. Breaking down the code into easily identifiable components with varying complexity and context is key to achieving this objective. This approach involves creating concise segments in some areas while accommodating lengthier and intricate sections in other parts. With this method, the asynchronous JavaScript is run in an efficient and optimized manner.

Learn How to use JavascriptExecutor

  • 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);

Implementation

Example

// importing the package
Import org.openqa.selenium.JavascriptExecutor;

// creating a reference
JavascriptExecutor js = (JavascriptExecutor) driver;

// calling the method
js.executeScript(script, args);

Examples of JavascriptExecutor in Selenium

Example 1

To refresh the browser window.

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("location.reload()");

Example 2

To send the text.

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("document.getElementByID(‘element id ’).value = ‘xyz’;");

Example 3

To generate the alert pop window.

JavascriptExecutor js = (JavascriptExecutor)driver;

Js.executeScript("alert(‘hello world’);");

Example 4

To get the Inner text of a web page.

avascriptExecutor js = (JavascriptExecutor)driver;

string sText =  js.executeScript("return document.documentElement.innerText;").toString();

Example 5

To get the title of the web page.

avascriptExecutor js = (JavascriptExecutor)driver;

string sText =  js.executeScript("return document.title;").toString();

Example 6

To scroll the page.

JavascriptExecutor js = (JavascriptExecutor)driver;

 //Vertical scroll – down by 150 pixels

 js.executeScript("window.scrollBy(0,150)");

Choose an element using javascriptExecutor

In this example, we are using selenium web driver and the javascriptExecutor to open WaytoClass website and click an element.

Explanation

The following mentioned script will launch edge browser, take you to the WaytoClass website, and use javascriptExecutor to click a certain element. So, let’s check how it functions.

  • Create an edge driver class and provide the path of youredgedriver.exe in the system property "webdriver.edge.driver".

  • Maximize the window by using driver.manage().window().maximize()

  • Open the URL using driver.get("URL link")

  • Get the element for Java using finddby xpath method "driver.findElement(By.xpath("xpath address"));"

  • Create a reference for javascriptExecutor by using javascriptExecutor js=(javascriptExecutor) driver;"

  • Call the javascriptExecutor method and pass the web element for clicking "js.executeScript("arguments[0].click();",webelement);"

Example

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
public class waytoclass {
   public static void main(String args[]) {
      System.setProperty(
         "webdriver.edge.driver",
         "C:\Users\ADMIN\Documents\Selenium\msedgedriver.exe");
	
      // Instantiate a Driver class.
      WebDriver driver = new EdgeDriver();
	
      // Maximize the browser
      driver.manage().window().maximize();
	
      // Launch Website
      driver.get("https://www.waytoclass.com/");
	
      WebElement java = driver.findElement(
         By.xpath("//*[@id="hslider"]/li[6]/a"));
	
      // Create a reference
      JavascriptExecutor js = (JavascriptExecutor)driver;
	
      // Call the JavascriptExecutor methods
      js.executeScript("arguments[0].click();", java);
   }
}

Output

Starting MSEdgeDriver 98.0.1108.56 (9a336a18ae89157b3c7ea0568a9cbced8ebc3f7) on port 55401
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping MSEdgeDriver safe. MSEdgeDriver was started successfully.

NOTE − After showing the above-mentioned output it will automatically open the website and click the element.

Conclusion

Enhancing automation capabilities on the web is made possible through the use of JavascriptExecutor allowing developers to engage with page elements beyond what is ordinarily feasible using Selenium. Moreover, with a higher degree of flexibility and customization added to the equation web automation can be greatly improved in terms of speed and efficiency. Despite its complexity for inexperienced coders who are not versed in the intricacies of JavaScript, mastering this language can enable organizations which strive towards advancing their internet persona.

Updated on: 01-Aug-2023

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements