Understanding execute async script in Selenium


We can use the executeAsyncScript method in Selenium webdriver. For an executeAsyncScript method, JavaScript Executor runs an asynchronous part of JavaScript with the reference to the present selected window or frame. In contrast to executeScript, the scripts which run with executeAsyncScript method, should be completed by invoking the given callback.

The callback is always added as the last argument within the executed function. The first argument passed is used to get the script result.If the script consists of a return statement, then the below rules are followed −

  • A webelement is returned for an HTML element.

  • A double is returned for a decimal number.

  • A long is returned for a non-decimal number.

  • A Boolean is returned for a Boolean number.

  • A string is returned for all the other cases.

  • A list of objects is returned following the above rules for an array.

  • If the value is null or there is nothing to return, a null is returned.

We can perform the below tasks with the executeAsyncScript method −

  • To set the browser timeout.

  • To synchronize a test with an AJAX application.

  • To inject an XMLHttpRequest and wait for the result.

The arguments of executeAsyncScript method can be Boolean, string, webelement, list or a number. An exception is raised, if the arguments are not of these types. The arguments shall be available using the arguments keyword.

Syntax

JavascriptExecutor j = (JavascriptExecutor) driver;
j.executeAsyncScript
("window.setTimeout(arguments[arguments.length - 1], 800);");

Example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ExecuteAsyncScriptMethod{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/index.htm");
      //get current system time
      long s = System.currentTimeMillis();
      // Javascript executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      //executeAsyncScript method to set timeout
      j.executeAsyncScript
      ("window.setTimeout(arguments[arguments.length - 1], 800);");
      System.out.println(
      "Time Elapsed is: " + (System.currentTimeMillis() - s));
      driver.quit();
   }
}

Output

Updated on: 01-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements