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
The main difference between those are that scripts executed with async must explicitly signal they are finished by invoking the provided callback. This callback is always injected into the executed function as the last argument.
will show the alert:
window.onload
makes sure the JS is executed when the page is loaded completely.I use
executeScript
. Example provided:Concerning details on alerts there is known issue. you can get details here
In accordance with documentation difference is:
Detailed documentation is here
I used lots of time to undertand this function and finally I got it. follwing code will help a lot:
(Keeping it simple, and correct.)
The relevant difference between
execteScript
andexecuteAsyncScript
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.
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' withexecuteAsyncScript
: "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.