WebDriver executeAsyncScript vs executeScript

vispart picture vispart · Nov 19, 2012 · Viewed 52.5k times · Source

What is the difference between executeAsyncScript and executeScript? How can i use event such as window.onload? I tried something like this

((JavascriptExecutor) driver).executeAsyncScript("window.onload = function() {alert('Hello')}"); 

But of course it did not work... So if anyone knows how it works please write an example

Answer

user2864740 picture user2864740 · Nov 22, 2015

(Keeping it simple, and correct.)

The relevant difference between execteScript and executeAsyncScript is this:

The function invoked with executeAsyncScript takes a 'done callback' as the last argument, which must be called to signal that the script is done executing.

This allows it to be used with code that only 'finishes' when a callback is used - eg. setTimeout or asynchronous XHR. If the 'done callback' is not called within the timeout limits the returned promise will be rejected.

Per the webdriver.WebDriver.executeAsyncScript documentation:

Unlike executing synchronous JavaScript with #executeScript, scripts executed with [#executeAsyncScript] must explicitly signal they are finished by invoking the provided callback. This callback will always be injected into the executed function as the last argument..

That is, both functions block the WebDriver control flow until they complete - either running off the end of the code for executeScript or when calling the 'done callback' with executeAsyncScript: "async" in the name signifies the signal mechanism used and does not mean/imply that the JavaScript code is actually executed asynchronously with respect to the WebDriver.