Page events
Learn how to react to JavaScript events in the page.
The built-in page fixture provides multiple events to monitor what's happening in your end-to-end tests. These events can be valuable to confirm alerts, catch log messages or monitor JavaScript exceptions.
page.on('dialog')
Confirm dialogs.
page.on("dialog", (dialog) => {
dialog.accept();
});
page.on('console')
Capture JavaScript console.log messages.
page.on("console", async (msg) => {
const values = [];
for (const arg of msg.args()) values.push(await arg.jsonValue());
console.log(...values);
});
// inject JavaScript into the page to trigger the event handler
await page.evaluate(() => console.log("hello", 5, { foo: "bar" }));
page.on('pageerror')
Log all uncaugt errors to the terminal.
page.on("pageerror", (exception) => {
console.log(`Uncaught exception: "${exception}"`);
});
// trigger an exception
await page.goto('data:text/html,<script>throw new Error("Test")</script>');
Note
There are way more page events to react to. Find more events in the Playwright documentation.
Exercise
Navigate the ecommerce site.
- Whenever you add the query param
?log=trueto a URL, the page will log to the console.
Todo
Solution
💡 If you're stuck, find a working example on GitHub.