JavascriptExecutor in Selenium WebDriver

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;
jsExecutor.executeScript("JavaScriptCode");

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-

@Test
public void testScroll() throws InterruptedException{

//Launch flipkart
driver.get("http://www.flipkart.com");

//Write the search term - Buddha in search box
WebElement searchBox = driver.findElement(By.id("fk-top-search-box"));
searchBox.sendKeys("Buddha");

//Click on searchButton
WebElement searchButton = driver.findElement(By.className("search-bar-submit"));
searchButton.click();

//Inserting an optional wait of 3 seconds just to notice scroll down event
Thread.sleep(3000);

//Scroll down the webpage by 2500 pixels
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("scrollBy(0, 2500)");

//Optional Wait
Thread.sleep(3000);
}

That’s all we have in this section, comment below if you have any queries. Also please share this post with your friends and don’t forget to check our complete selenium tutorial here.

Selenium Tutorial

От QA genius

Adblock
detector