execute
使用給定的元素作為範圍,將一段 JavaScript 片段注入到頁面中以在目前選取的框架中執行,由於它在元素範圍內,這表示 WebdriverIO 會在執行腳本之前自動等待元素存在。假設執行的腳本是同步的,並且評估腳本的結果會返回給用戶端。
script 引數定義了要執行的腳本,形式為函數主體。該函數返回的值將會返回給用戶端。該函數將使用提供的 args 陣列調用,並且可以透過引數物件依指定的順序存取這些值。
引數可以是任何 JSON 基本類型、陣列或 JSON 物件。定義 WebElement 參照的 JSON 物件將會轉換為對應的 DOM 元素。同樣地,腳本結果中的任何 WebElement 都會以 WebElement JSON 物件的形式返回給用戶端。
用法
$(selector).execute(script, arguments)
參數
名稱 | 類型 | 詳細資訊 |
---|---|---|
script | String , Function | 要執行的腳本。 |
arguments 選填 | param | 腳本引數 |
範例
execute.js
it('should wait for the element to exist, then executes javascript on the page with the element as first argument', async () => {
const text = await $('div').execute((elem, a, b, c, d) => {
return elem.textContent + a + b + c + d
}, 1, 2, 3, 4);
// node.js context - client and console are available
console.log(text); // outputs "Hello World1234"
});