Selenium and asynchronous JavaScript calls Selenium and asynchronous JavaScript calls selenium selenium

Selenium and asynchronous JavaScript calls


For asynchronous code you have to use executeAsyncScript:

JavascriptExecutor js = (JavascriptExecutor) driver; String docInfoVal = (String) js.executeAsyncScript("" +        "var done = arguments[0]; " +        "getCurrentDocumentInfo(\"somestuff\"," +            "function(docId) {" +                "done(docId);" +            "}" +        ");");

The script you call with executeAsyncScript will have a callback added to the list of arguments passed to it. Since you pass no arguments to your script, then arguments[0] contains the callback. Your code must call this callback when it is done working. The value you give to the callback is the value that executeAsyncScript returns.

In the code above, I've spelled out the call to done by putting it in an anonymous function but the code could be written more concisely as:

JavascriptExecutor js = (JavascriptExecutor) driver; String docInfoVal = (String) js.executeAsyncScript("" +        "var done = arguments[0]; " +        "getCurrentDocumentInfo(\"somestuff\", done);");

Or even:

JavascriptExecutor js = (JavascriptExecutor) driver; String docInfoVal = (String) js.executeAsyncScript(        "getCurrentDocumentInfo('somestuff', arguments[0]);");


Though this is almost same as what @Louis said.You have to set the setScriptTimeout beforehand for the script to pass.

The default timeout for a script to be executed is 0ms. In most cases, including the examples below, one must set the script timeout WebDriver.Timeouts.setScriptTimeout(long, java.util.concurrent.TimeUnit) beforehand to a value sufficiently large enough.

Below is an example for which I'm waiting for 10 seconds to return a string

  driver.manage().timeouts().setScriptTimeout(20, TimeUnit.SECONDS);//important    JavascriptExecutor executor = (JavascriptExecutor) driver;    String val = (String) executor.executeAsyncScript(""            + "var done=arguments[0]; "            + "setTimeout(function() {"            + "   done('tada');"            + "  }, 10000);");    System.out.println(val);