Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be asynchronous.

The function to be injected receives the done callback as argument which needs to be called when the asynchronous operation finishes. The value passed to the done callback is returned to the client.
Additional arguments for the injected function may be passed as a non-empty array which will be passed before the done callback.

Asynchronous script commands may not span page loads. If an unload event is fired while waiting for the script result, an error will be returned.

Usage

                    .executeAsync(body, [args], [callback])
                
                    .executeAsyncScript(body, [args], [callback])
                
                    .document.executeAsync(body, [args], [callback])
                
                    .document.executeAsyncScript(body, [args], [callback])
                

Example

describe('execute async script', function() {
  it('executes async script in browser', function(browser) {
    browser.executeAsyncScript(function(done) {
      setTimeout(function() {
        done(true);
      }, 500);
    }, function(result) {
      // whatever is passed to the `done` callback in the script above
      // will be available as result.value
      console.log(result.value); // true
    });
  });

  it('executes a script with ES6 async/await', async function(browser) {
    const result = await browser
      .document.executeAsync(function(arg1, arg2, done) {
        setTimeout(function() {
          done(arg1);
        }, 500);
      }, [arg1, arg2]);

    // whatever is passed to the `done` callback in the script above
    // will be returned by the command when used with `await`.
    console.log(result); // arg1
  });
});

Parameters

Name Type description
body string | function

The function body to be injected.

args Array

An array of arguments which will be passed to the function.

callback
Optional
function

Optional callback function to be called when the command finishes.

Returns

Type description
*

The script result.

See also

W3C WebDriver spec