Execute JavaScript with executeAsyncScript() Method in Selenium

HOME

In the previous blog, we have discussed about executeScript() method in JavaScript. JavascriptExecutor interface comprises of executeAsyncScript() method that is called an additional final argument “arguments[arguments.lenght-1];”which is a callback function to signal that async execution has finished. We have to call from JavaScript, to tell Webdriver, that our Asynchronous execution has finished. If we do not do that, then executeAsyncScpriptwill timeout and throw a timeout exception.

Before executing AsyncScript method, we have to make sure to set the script timeout. Its default is 0. If we do not set a script timeout, our executeAsyncScript will immediately timeout and it won’t work.

Below is the program which shows how to use executeAsyncScript() method

  1. First  will get the start time before waiting 5 seconds by using executeAsyncScript() method.
  2. Then, will use executeAsyncScript() to wait 5 seconds.
  3. Then, will get the current time
  4. Will subtract (current time – start time) = passed time and print the value
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public classExecuteAsycSleepBrowserDemo {
        public static void main(String[] args) { 
    

System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = newChromeDriver();
                                        
        //Create the JavascriptExecutor interface object by Type casting              
        JavascriptExecutor js = (JavascriptExecutor)driver;              
        driver.get("https://www.google.com/");                              
        driver.manage().window().maximize();
                        
        //Declare and set start time
        long startTime = System.currentTimeMillis();
                 
        //Call executeAsyncScript() method                       js.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 5000);"); 
                 
        //Get the difference (currentTime - startTime) it should be greater than 5000
        System.out.println("Passed time: " + (System.currentTimeMillis() - startTime));
                        
          if ( (System.currentTimeMillis() - startTime) > 5000)
             {
                 System.out.println("Time difference must be greater than 5000 milliseconds");
             }
          driver.quit();      
      }

Output
Passed time: 5040
Time difference must be greater than 5000 milliseconds

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s