將一段 JavaScript 片段注入頁面中,以便在目前選取的框架的上下文中執行。執行的腳本假定為同步。
script 引數定義要執行的腳本,其形式為函式主體。該函式傳回的值將傳回給用戶端。

將使用提供的 args 陣列呼叫該函式,並且可以依照指定的順序透過 arguments 物件存取這些值。

在底層,如果 body 參數是函式,則會使用 function.toString() 將其轉換為字串。任何對您目前範圍的參照都將被忽略。

為了確保跨瀏覽器相容性,指定的函式不應採用 ES6 格式(即 () => {})。如果函式的執行失敗,回呼的第一個引數包含錯誤資訊。

用法

                    .execute(body, [args], [callback])
                
                    .executeScript(body, [args], [callback])
                
                    .document.execute(body, [args], [callback])
                
                    .document.executeScript(body, [args], [callback])
                

範例

describe('execute script', function() {
  it('executes a script in browser', function(browser) {
    browser.executeScript(function(imageData) {
      // resize operation
      return true;
    }, [imageData], function(result) {
      // whatever is returned by the script passed above will be available
      // as result.value
      console.log(result.value); // true
    });

    // scroll to the bottom of the page.
    browser.executeScript('window.scrollTo(0,document.body.scrollHeight);');
  });

  it('executes a script with ES6 async/await', async function(browser) {
    const result = await browser
      .document.executeScript(function(imageData) {
        // resize operation
        return true;
      }, [imageData]);

    console.log(result); // true
  });
});

參數

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

要注入的函式主體。

args 陣列

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

callback
選用
函式

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

傳回

類型 描述
*

腳本結果。

另請參閱

W3C WebDriver 規格