How to Execute Javascript in Webdriver using Javascriptexecutor using executeAsyncScript method?
JavaScriptExecutor can be used to execute javascript in WebDriver. JavaScriptExecutor actions like the way Xpath, Link, CSS, Id locators works in Selenium Webdriver.
javaScriptExecutor is supported by Selenium library and for that you need to import ‘org.openqa.selenium.JavascriptExecutor ‘ in your program.
In Selenium, javaScriptExecutor works like an interface and facilitates Javascript execution in there.
JavaScriptExecutor has two methods and one of the method is as below,
1) executeAsyncScript – This method will not block the execution of next line of code. Page rendering is fast here.
example:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeAsyncScript(Script,Arguments);
Example for executeAsyncScript
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class ExecuteAsyncScriptExample {
@Test
public void ExecuteAsyncScriptTest()
{
WebDriver driver= new FirefoxDriver();
JavascriptExecutor js = (JavascriptExecutor)driver;
driver.get(“your website url”);
driver.manage().window().maximize();
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
long BeginTime = System.currentTimeMillis();
//executeAsyncScript() method is used to enable 10 seconds wait.
js.executeAsyncScript(“window.setTimeout(arguments[arguments.length – 1], 10000);”);
long EndTime = System.currentTimeMillis();
System.out.println(“Passed time: ” + (EndTime – BeginTime));
}
}