JavascriptExecutor in Selenium WebDriver

In this post, we will study - how to execute javascript code in Selenium webdriver and find the scenarios where we need to use the javascript code instead of the different methods of selenium.

Need of Executing JavaScript Code

JavaScript is a lightweight interpreted language for client side scripting. In automation, we might need JavaScript code execution for following reasons-

  1. JavaScript executor is particularly used to handle scenarios including hidden web elements which cannot be located by Selenium WebDriver locators.
  2. For handling test scenarios requiring explicit javascript code execution.
  3. For performing operations like - "Scrolling a web page" which can be easily performed using Javascript.

JavaScriptExecutor in Selenium WebDriver

The JavaScriptExecutor is an interface in Selenium WebDriver that is implemented by FirefoxDriver, InternetExplorerDriver, ChromeDriver and other driver classes. Using JavaScriptExecutor, we can execute a JavaScript code with Selenium WebDriver.

Methods of JavaScriptExecutor

The JavaScriptExecutor provides two methods of javaScript code injection in browser-
1. executeScript() - To run the specified JavaScript code in the current window or frame.

JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;

2. executeAsyncScript() - To run specified asynchronous JavaScript code in the current window or frame. As the javaScript runs asynchronously, it requires an explicit callback indicating the finishing of script execution.

JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
jsExecutor.executeAsyncScript("Async JavaScript Code");

Sample Script for JavaScriptExecuter

Scrolling a web page in Selenium WebDriver using JavaScriptExecuter-

public void testScroll() throws InterruptedException{
	//Launch flipkart
	//Write the search term - Buddha in search box
	WebElement searchBox = driver.findElement("fk-top-search-box"));
	//Click on searchButton
	WebElement searchButton = driver.findElement(By.className("search-bar-submit"));;
	//Inserting an optional wait of 3 seconds just to notice scroll down event
	//Scroll down the webpage by 2500 pixels
	JavascriptExecutor js = (JavascriptExecutor)driver;
	js.executeScript("scrollBy(0, 2500)"); 
	//Optional Wait