JavaScript の評価
概要
Playwright スクリプトは Playwright 環境で実行されます。ページスクリプトはブラウザページ環境で実行されます。これらの環境は交差せず、異なる仮想マシン、異なるプロセス、場合によっては異なるコンピュータ上で実行されています。
Page.evaluate() API は、ウェブページのコンテキストで JavaScript 関数を実行し、結果を Playwright 環境に戻すことができます。window
や document
のようなブラウザグローバルは evaluate
で使用できます。
String href = (String) page.evaluate("document.location.href");
結果が Promise の場合、または関数が非同期の場合、evaluate は自動的に解決されるまで待機します。
int status = (int) page.evaluate("async () => {\n" +
" const response = await fetch(location.href);\n" +
" return response.status;\n" +
"}");
異なる環境
評価されたスクリプトはブラウザ環境で実行され、テストはテスト環境で実行されます。これは、テストの変数をページで使用したり、その逆も同様にできないことを意味します。代わりに、引数として明示的に渡す必要があります。
次のスニペットは、変数を直接使用しているため、間違っています。
String data = "some data";
Object result = page.evaluate("() => {\n" +
" // WRONG: there is no 'data' in the web page.\n" +
" window.myApp.use(data);\n" +
"}");
次のスニペットは、値を引数として明示的に渡しているため、正しいです。
String data = "some data";
// Pass |data| as a parameter.
Object result = page.evaluate("data => {\n" +
" window.myApp.use(data);\n" +
"}", data);
評価引数
Page.evaluate() のような Playwright 評価メソッドは、単一のオプションの引数を取ります。この引数は、シリアライズ可能な値と JSHandle インスタンスの組み合わせにすることができます。ハンドルは、それらが表す値に自動的に変換されます。
// A primitive value.
page.evaluate("num => num", 42);
// An array.
page.evaluate("array => array.length", Arrays.asList(1, 2, 3));
// An object.
Map<String, Object> obj = new HashMap<>();
obj.put("foo", "bar");
page.evaluate("object => object.foo", obj);
// A single handle.
ElementHandle button = page.evaluateHandle("window.button");
page.evaluate("button => button.textContent", button);
// Alternative notation using JSHandle.evaluate.
button.evaluate("(button, from) => button.textContent.substring(from)", 5);
// Object with multiple handles.
ElementHandle button1 = page.evaluateHandle("window.button1");
ElementHandle button2 = page.evaluateHandle("window.button2");
Map<String, ElementHandle> arg = new HashMap<>();
arg.put("button1", button1);
arg.put("button2", button2);
page.evaluate("o => o.button1.textContent + o.button2.textContent", arg);
// Object destructuring works. Note that property names must match
// between the destructured object and the argument.
// Also note the required parenthesis.
Map<String, ElementHandle> arg = new HashMap<>();
arg.put("button1", button1);
arg.put("button2", button2);
page.evaluate("({ button1, button2 }) => button1.textContent + button2.textContent", arg);
// Array works as well. Arbitrary names can be used for destructuring.
// Note the required parenthesis.
page.evaluate(
"([b1, b2]) => b1.textContent + b2.textContent",
Arrays.asList(button1, button2));
// Any mix of serializables and handles works.
Map<String, Object> arg = new HashMap<>();
arg.put("button1", button1);
arg.put("list", Arrays.asList(button2));
arg.put("foo", 0);
page.evaluate(
"x => x.button1.textContent + x.list[0].textContent + String(x.foo)",
arg);
初期化スクリプト
ページがロードを開始する前に何かを評価すると便利な場合があります。たとえば、モックやテストデータをセットアップしたい場合があります。
この場合、Page.addInitScript() または BrowserContext.addInitScript() を使用します。以下の例では、Math.random()
を定数値に置き換えます。
まず、モックを含む preload.js
ファイルを作成します。
// preload.js
Math.random = () => 42;
次に、初期化スクリプトをページに追加します。
// In your test, assuming the "preload.js" file is in the "mocks" directory.
page.addInitScript(Paths.get("mocks/preload.js"));