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 ofExecuteScript
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 ofExample
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);"
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.
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!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools