イベント
はじめに
Playwright を使用すると、ネットワークリクエスト、子ページの作成、専用ワーカーなど、Web ページで発生するさまざまな種類のイベントをリッスンできます。 イベントを待機したり、イベントリスナーを追加または削除するなど、このようなイベントをサブスクライブする方法はいくつかあります。
イベントを待つ
ほとんどの場合、スクリプトは特定のイベントが発生するのを待つ必要があります。 以下に、一般的なイベント待機パターンをいくつか示します。
Page.waitForRequest() を使用して、指定された URL のリクエストを待ちますPage.waitForRequest()
// The callback lambda defines scope of the code that is expected to
// trigger request.
Request request = page.waitForRequest("**/*logo*.png", () -> {
page.navigate("https://wikipedia.org");
});
System.out.println(request.url());
ポップアップウィンドウを待つ
// The callback lambda defines scope of the code that is expected to
// create popup window.
Page popup = page.waitForPopup(() -> {
page.getByText("open the popup").click();
});
popup.navigate("https://wikipedia.org");
イベントリスナーの追加/削除
イベントはランダムな時間に発生することがあり、イベントを待つ代わりに、処理する必要があります。 Playwright は、イベントのサブスクライブとサブスクライブ解除のための従来の言語メカニズムをサポートしています。
page.onRequest(request -> System.out.println("Request sent: " + request.url()));
Consumer<Request> listener = request -> System.out.println("Request finished: " + request.url());
page.onRequestFinished(listener);
page.navigate("https://wikipedia.org");
// Remove previously added listener, each on* method has corresponding off*
page.offRequestFinished(listener);
page.navigate("https://www.openstreetmap.org/");
1 回限りのリスナーの追加
特定のイベントを 1 回処理する必要がある場合は、便利な API があります。
page.onceDialog(dialog -> dialog.accept("2021"));
page.evaluate("prompt('Enter a number:')");