Need of Executing JavaScript Code
JavaScript is a lightweight deciphered language for customer side scripting. In robotization, we may require JavaScript code execution for following reasons-
- JavaScript agent is especially used to deal with situations including shrouded web components which can't be situated by Selenium WebDriver locators.
- For taking care of test situations requiring unequivocal javascript code execution.
- For performing activities like – "Looking over a page" which can be handily performed utilizing Javascript.
JavaScriptExecutor in Selenium WebDriver
The JavaScriptExecutor is an interface in Selenium WebDriver that is actualized by FirefoxDriver, InternetExplorerDriver, ChromeDriver and other driver classes. Utilizing JavaScriptExecutor, we can execute a JavaScript code with Selenium WebDriver.
Methods of JavaScriptExecutor
The JavaScriptExecutor gives two strategies for javaScript code infusion in program
1. executeScript() – To run the predefined JavaScript code in the present window or casing.
JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
jsExecutor.executeScript("JavaScriptCode");
2. executeAsyncScript() – To run indicated offbeat JavaScript code in the present window or casing. As the javaScript runs nonconcurrently, it requires an express callback demonstrating the completing of content execution.
JavascriptExecutor jsExecutor = (JavascriptExecutor)driver;
jsExecutor.executeAsyncScript("Async JavaScript Code");
Sample Script for JavaScriptExecuter
Looking over a website page in Selenium WebDriver utilizing 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 is all we have in this area, remark beneath in the event that you have any inquiries. Additionally please share this post with your companions and remember to check our total selenium instructional exercise here.