Selenium Course
- 61k Enrolled Learners
- Weekend/Weekday
- Live Class
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.
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:
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.
The two main components of JavaScriptExecutor in Selenium are:
1. executeScript
2. executeAsyncScript
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.
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);
When you use JavascriptExecutor in Selenium, as stated above, it works in the following way:
JS Executor in Selenium is commonly used in several cases. It is helpful for simulating user interactions with HTML elements in test scripts.
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:
Let’s understand the use of JavascriptExecutor in Selenium with some common examples.
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.
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.
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>
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.
To execute the example codes mentioned above, you need to download Selenium, Java SDK, Eclipse IDE, and Chrome driver.
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.
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.
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.
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.
Course Name | Date | Details |
---|---|---|
Selenium Course | Class Starts on 19th October,2024 19th October SAT&SUN (Weekend Batch) | View Details |
Selenium Course | Class Starts on 28th October,2024 28th October MON-FRI (Weekday Batch) | View Details |
Selenium Course | Class Starts on 25th November,2024 25th November MON-FRI (Weekday Batch) | View Details |
edureka.co