Playwright allows listening to various types of events happening on the web page, such as network requests, creation of child pages, dedicated workers etc. There are several ways to subscribe to such events, such as waiting for events or adding or removing event listeners.
Waiting for eventMost of the time, scripts will need to wait for a particular event to happen. Below are some of the typical event awaiting patterns.
Wait for a request with the specified url using Page.waitForRequest():
Request request = page.waitForRequest("**/*logo*.png", () -> {
page.navigate("https://wikipedia.org");
});
System.out.println(request.url());
Wait for popup window:
Page popup = page.waitForPopup(() -> {
page.getByText("open the popup").click();
});
popup.navigate("https://wikipedia.org");
Adding/removing event listener
Sometimes, events happen in random time and instead of waiting for them, they need to be handled. Playwright supports traditional language mechanisms for subscribing and unsubscribing from the events:
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");
page.offRequestFinished(listener);
page.navigate("https://www.openstreetmap.org/");
Adding one-off listeners
If a certain event needs to be handled once, there is a convenience API for that:
page.onceDialog(dialog -> dialog.accept("2021"));
page.evaluate("prompt('Enter a number:')");
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4