Home  >  Article  >  Java  >  JavascriptExecutor in Selenium

JavascriptExecutor in Selenium

王林
王林forward
2023-08-19 19:21:091075browse

Selenium is a well-known open source, web-based automation tool used by many people. But sometimes it has problems interacting with certain elements; perhaps an unexpected popup prevents the web driver from performing its actions and generates incorrect results. This is where JavascriptExecutor plays a key role in this scenario, enabling the web driver to successfully perform the required operations. Its complexity and suddenness make it easier to deal with the situation.

What is JavascriptExecutor in Selenium?

Using an interface called JavascriptExecutor, you can execute JavaScript through Selenium and interact with HTML in the browser when using this programming language. You must use JavascriptExecutor objects to create sentence structures of varying length and complexity for composition Engaging text is crucial. Thus, the JavaScript Executor provides a means to communicate with HTML within a web browser, while also enabling programmers to use their own unique JavaScript writing style to build clever and flexible expressions.

Methods

The following are the methods provided by JavascriptExecutor in Selenium:

The Chinese translation of

ExecuteScript

is:

execute script

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

  • Web Elements

  • Lists

  • Strings

  • Long

  • Boolean value

  • 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 package

import org.openqa.selenium.JavascriptExecutor;
  • Step 2 - Create a reference

javascriptExecutor js = (JavascriptExecutor) driver;
  • Step 3 - Call JavascriptExecutor method

js.executeScript(script, args);

Implementation

The Chinese translation of

Example

is:

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

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

Generate warning pop-up 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();
The Chinese translation of

Example 6

is:

Example 6

Scroll the page.

JavascriptExecutor js = (JavascriptExecutor)driver;

 //Vertical scroll – down by 150 pixels

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

Use javascriptExecutor to select an element

In this example, we use selenium web driver and javascriptExecutor to open the WaytoClass website and click on 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()

  • Use driver.get("URL link") to open the URL

  • Use the finddby xpath method to get the Java element "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 page element to be clicked "js.executeScript("arguments[0].click();",webelement);"

The Chinese translation of

Example

is:

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 output, it will automatically open the website and click on the element.

JavascriptExecutor in Selenium

in 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.

The above is the detailed content of JavascriptExecutor in Selenium. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete
Previous article:Node.js vs JavaNext article:Node.js vs Java