<T>
executeAsyncScript(script, var_args)code »
Schedules a command to execute asynchronous JavaScript in the context of the currently selected frame or window. The script fragment will be executed as the body of an anonymous function. If the script is provided as a function object, that function will be converted to a string for injection into the target window.
Any arguments provided in addition to the script will be included as script arguments and may be referenced using the arguments
object. Arguments may be a boolean, number, string, or webdriver.WebElement
. Arrays and objects may also be used as script arguments as long as each item adheres to the types previously mentioned.
Unlike executing synchronous JavaScript with #executeScript
, scripts executed with this function 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, and thus may be referenced with arguments[arguments.length - 1]
. The following steps will be taken for resolving this functions return value against the first argument to the script's callback function:
- For a HTML element, the value will resolve to a
webdriver.WebElement
- Null and undefined return values will resolve to null
- Booleans, numbers, and strings will resolve as is
- Functions will resolve to their string representation
- For arrays and objects, each member item will be converted according to the rules above
Example #1: Performing a sleep that is synchronized with the currently selected window:
var start = new Date().getTime();
driver.executeAsyncScript(
'window.setTimeout(arguments[arguments.length - 1], 500);').
then(function() {
console.log(
'Elapsed time: ' + (new Date().getTime() - start) + ' ms');
});
Example #2: Synchronizing a test with an AJAX application:
var button = driver.findElement(By.id('compose-button'));
button.click();
driver.executeAsyncScript(
'var callback = arguments[arguments.length - 1];' +
'mailClient.getComposeWindowWidget().onload(callback);');
driver.switchTo().frame('composeWidget');
driver.findElement(By.id('to')).sendKeys('dog@example.com');
Example #3: Injecting a XMLHttpRequest and waiting for the result. In this example, the inject script is specified with a function literal. When using this format, the function is converted to a string for injection, so it should not reference any symbols not defined in the scope of the page under test.
driver.executeAsyncScript(function() {
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open("GET", "/resource/data.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
}
xhr.send('');
}).then(function(str) {
console.log(JSON.parse(str)['food']);
});
Parameters
- script
(string|Function)
The script to execute.
- var_args
...*
The arguments to pass to the script.