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.

Parameters

Name Type description
script 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.

Usage

 this.demoTest = function (browser) {
   browser.executeAsync(function(done) {
     setTimeout(function() {
       done(true);
     }, 500);
   }, function(result) {
     // result.value === true
   });

   browser.executeAsync(function(arg1, arg2, done) {
     setTimeout(function() {
       done(true);
     }, 500);
   }, [arg1, arg2], function(result) {
     // result.value === true
   });
}

Example


module.exports = {
  before : function(browser) {
    // see https://github.com/nightwatchjs/nightwatch/blob/main/examples/globalsModule.js#L12
    browser.globals.waitForConditionTimeout = 5000;
  },

  'executeAsync example test' : function (browser) {

    browser
      .timeoutsAsyncScript(10000)
      .executeAsync(function (inputVal, done) {
          // ... do stuff with window ...
          setTimeout(done, 5000, 'result');
        },
        ['input'],
        function (resultVal) {
          console.log('result =', resultVal);
        }
      );
  },

  after : function(browser) {
    browser.end();
  }
};

W3C WebDriver spec: