メインコンテンツへスキップ

イベント

はじめに

Playwrightでは、ネットワークリクエスト、子ページの作成、専用ワーカーなど、ウェブページで発生する様々な種類のイベントをリッスンできます。イベントの待機、イベントリスナーの追加または削除など、これらのイベントを購読するにはいくつかの方法があります。

イベントの待機

ほとんどの場合、スクリプトは特定のイベントが発生するのを待つ必要があります。以下に、一般的なイベント待機パターンをいくつか示します。

指定された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/");

一度限りのリスナーの追加

特定のイベントを一度だけ処理する必要がある場合、そのための便利なAPIがあります。

page.onceDialog(dialog -> dialog.accept("2021"));
page.evaluate("prompt('Enter a number:')");