How to use JavascriptExecutor in Selenium
By Mohammad Waseem, Community Contributor - February 7, 2023
Selenium is an automation testing tool that is also used for web browser automation testing. But, sometimes, Selenium WebDriver can encounter problems interacting with a few web elements. For instance, the user opens a URL and there is an unexpected pop-up that will prevent the WebDriver from locating a specific element and produce inaccurate results. This is where JavascriptExecutor comes into the picture.
What is JavascriptExecutor in Selenium?
In simple words, JavascriptExecutor is an interface that is used to execute JavaScript with Selenium. To simplify the usage of JavascriptExecutor in Selenium, think of it as a medium that enables the WebDriver to interact with HTML elements within the browser. JavaScript is a programming language that interacts with HTML in a browser, and to use this function in Selenium, JavascriptExecutor is required.
Let’s take a look at various components.
Components of JavascriptExecutor in Selenium
JavascriptExecutor consists of two methods that handle all essential interactions using JavaScript in Selenium.
- executeScript method – This method executes the test script in the context of the currently selected window or frame. The script in the method runs as an anonymous function. If the script has a return statement, the following values are returned:
- For an HTML element, the method returns a WebElement.
- For a decimal, the method returns Long.
- For a non-decimal number, the method returns Long.
- For a Boolean, the method returns Boolean.
- For other cases, the method returns a String.
- executeAsyncScript method – This method executes the asynchronous piece of JavaScript on the current window or frame. An asynchronous script will be executed while the rest of the page continues parsing, which enhances responsiveness and application performance.
How to get started with JavascriptExecutor
- Import the package
- Create a reference
- Call the JavascriptExecutor methods
[java] //importing the package Import org.openqa.selenium.JavascriptExecutor; //creating a reference JavascriptExecutor js = (JavascriptExecutor) driver; //calling the method js.executeScript(script, args); [/java]
Now, let’s examine various scenarios where JavascriptExecutor can be used to perform different operations.
How JavascriptExecutor works in Selenium
Let’s try to understand the working of JavascriptExecutor using a simple example and implementation of both the JavascriptExecutor methods.
- JavascriptExecutor in Selenium to click a button
[java] js.executeScript(“document.getElementByID(‘element id ’).click();”); [/java]
- JavascriptExecutor in Selenium to send text
[java] js.executeScript(“document.getElementByID(‘element id ’).value = ‘xyz’;”); [/java]
- JavascriptExecutor in Selenium to interact with checkbox
[java] js.executeScript(“document.getElementByID(‘element id ’).checked=false;”); [/java]
- JavascriptExecutor in Selenium to refresh the browser window
[java] js.executeScript(“location.reload()”); [/java]
The above code snippets show the syntax to perform specific operations.
Now, let’s understand why it is important to use JavascriptExecutor in Selenium.
Read More: Page Object Model in Selenium and JavaScript
Why use JavascriptExecutor in Selenium?
Sometimes, Selenium WebDriver alone will not be able to perform certain operations or interact with web elements. In that case, JavaScript is needed to make sure those actions are being performed accurately. To understand its importance, let’s consider an example.
Let’s suppose a tester has written an automation script to click a few buttons, but there seems to be an issue due to which the script fails every time. To resolve this, the tester uses JavascriptExecutor.
Use Case Scenarios
To explain the concept of JavascriptExecutor, let’s look at two simple use cases:
Example 1
Problem Statement: Generate an alert window using JavascriptExecutor.
Objective: Create a login automation script using Selenium that generates an alert window using JavascriptExecutor methods.
Code:
[java] package newpackage; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; import org.openqa.selenium.JavascriptExecutor; public class LoginAutomation { @Test public void login() { System.setProperty("webdriver.chrome.driver", "path"); WebDriver driver = new ChromeDriver(); JavascriptExecutor js = (JavascriptExecutor)driver; driver.manage().window().maximize(); driver.get("https://www.browserstack.com/users/sign_in"); js.executeScript("document.getElementById('user_email_login').value='rbc@xyz.com';"); js.executeScript("document.getElementById('user_password').value='password';"); js.executeScript("document.getElementById('user_submit').click();"); js.executeScript("alert('enter correct login credentials to continue');"); sleep(2000); } public static void sleep(int ms) { try { Thread.sleep(ms); } catch(InterruptedException e) { e.printStackTrace(); } } } [/java]
Output:
Once the code runs, Selenium will automatically navigate to the URL mentioned. First, the driver will open the browser and the URL. After that, the credentials will be entered using the JavascriptExecutor’s executeScript method. Finally, the login button is clicked. In the end, a pop-up will appear stating the message written in the alert() method.
Example 2
Let’s look at another example, which uses the executeAsyncScript method to scroll down to the bottom of a webpage.
Code:
[java] package newpackage; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.Test; import org.openqa.selenium.JavascriptExecutor; public class LoginAutomation { @Test public void login() { System.setProperty("webdriver.chrome.driver", "C:\\Users\\Pictures\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); JavascriptExecutor js = (JavascriptExecutor)driver; driver.manage().window().maximize(); driver.get("https://www.browserstack.com"); js.executeAsyncScript("window.scrollBy(0,document.body.scrollHeight)"); } } [/java]
Output:
The program opens the web browser and navigates to the URL- browserstack.com. After that, using the executeAsyncScript method from the JavascriptExecutor package, the script scrolls to the bottom of the webpage.
Conclusion
Considering the issues that Selenium sometimes faces in web browser automation while interacting with web elements, learning how to use JavascriptExecutor methods is imperative for Selenium testers. The implementation of both methods – executeScript and executeAsyncScript is a perfect solution that efficiently solves the problem of any potential issues.