將 JavaScript 片段注入頁面,以便在目前選定框架的內容中執行。假設執行的腳本是異步的。

要注入的函式會收到 done 回呼作為參數,該參數需要在異步操作完成時呼叫。傳遞給 done 回呼的值會傳回給用戶端。
注入函式的其他引數可以以非空陣列的形式傳遞,這些引數會在 done 回呼之前傳遞。

異步腳本命令可能不會跨越頁面載入。如果在等待腳本結果時觸發卸載事件,則會傳回錯誤。

用法

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

範例

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
  });
});

參數

名稱 類型 描述
body 字串 | 函式

要注入的函式主體。

args 陣列

將傳遞給函式的引數陣列。

callback
可選
函式

命令完成時呼叫的可選回呼函式。

傳回

類型 描述
*

腳本結果。

另請參閱

W3C WebDriver 規範