跳到主要內容

評估 JavaScript

簡介

Playwright 腳本在您的 Playwright 環境中執行。您的頁面腳本在瀏覽器頁面環境中執行。這些環境不會互相干擾,它們在不同的虛擬機器、不同的程序中執行,甚至可能在不同的電腦上執行。

Page.EvaluateAsync() API 可以在網頁的上下文中執行 JavaScript 函數,並將結果帶回 Playwright 環境。瀏覽器全域物件,例如 windowdocument,可以在 evaluate 中使用。

var href = await page.EvaluateAsync<string>("document.location.href");

如果結果是 Promise,或者如果函數是異步的,evaluate 將自動等待直到它被解析

int status = await page.EvaluateAsync<int>(@"async () => {
const response = await fetch(location.href);
return response.status;
}");

不同的環境

評估的腳本在瀏覽器環境中執行,而您的測試在測試環境中執行。這表示您無法在頁面中使用測試中的變數,反之亦然。相反地,您應該將它們明確地作為引數傳遞。

以下程式碼片段是錯誤的,因為它直接使用變數

var data = "some data";
var result = await page.EvaluateAsync(@"() => {
// WRONG: there is no 'data' in the web page.
window.myApp.use(data);
}");

以下程式碼片段是正確的,因為它明確地將值作為引數傳遞

var data = "some data";
// Pass |data| as a parameter.
var result = await page.EvaluateAsync("data => { window.myApp.use(data); }", data);

評估引數

Playwright 評估方法,例如 Page.EvaluateAsync(),接受單一選用引數。此引數可以是 可序列化 值和 JSHandle 實例的混合。處理器會自動轉換為它們代表的值。

// A primitive value.
await page.EvaluateAsync<int>("num => num", 42);

// An array.
await page.EvaluateAsync<int[]>("array => array.length", new[] { 1, 2, 3 });

// An object.
await page.EvaluateAsync<object>("object => object.foo", new { foo = "bar" });

// A single handle.
var button = await page.EvaluateHandleAsync("window.button");
await page.EvaluateAsync<IJSHandle>("button => button.textContent", button);

// Alternative notation using JSHandle.EvaluateAsync.
await button.EvaluateAsync<string>("(button, from) => button.textContent.substring(from)", 5);

// Object with multiple handles.
var button1 = await page.EvaluateHandleAsync("window.button1");
var button2 = await page.EvaluateHandleAsync("window.button2");
await page.EvaluateAsync("o => o.button1.textContent + o.button2.textContent", new { button1, button2 });

// Object destructuring works. Note that property names must match
// between the destructured object and the argument.
// Also note the required parenthesis.
await page.EvaluateAsync("({ button1, button2 }) => button1.textContent + button2.textContent", new { button1, button2 });

// Array works as well. Arbitrary names can be used for destructuring.
// Note the required parenthesis.
await page.EvaluateAsync("([b1, b2]) => b1.textContent + b2.textContent", new[] { button1, button2 });

// Any mix of serializables and handles works.
await page.EvaluateAsync("x => x.button1.textContent + x.list[0].textContent + String(x.foo)", new { button1, list = new[] { button2 }, foo = null as object });

初始化腳本

有時在頁面開始載入之前評估某些內容會很方便。例如,您可能想要設定一些模擬或測試資料。

在這種情況下,請使用 Page.AddInitScriptAsync()BrowserContext.AddInitScriptAsync()。在下面的範例中,我們將把 Math.random() 替換為常數值。

首先,建立一個包含模擬的 preload.js 檔案。

// preload.js
Math.random = () => 42;

接下來,將初始化腳本添加到頁面。

// In your test, assuming the "preload.js" file is in the "mocks" directory.
await Page.AddInitScriptAsync(scriptPath: "mocks/preload.js");