Handling the Dialogs
Introduction
The Playwright framework is capable of interacting with web page dialogs, including alert, confirm, and prompt, in addition to beforeunload confirmation. For print dialogs, see Print.
alert(), confirm(), prompt() dialogs
By default, Playwright automatically dismisses dialogs, eliminating the need for you to manage them. Nevertheless, you have the option to register a dialog handler prior to the action that initiates the dialog, allowing you to either dialog.accept() or dialog.dismiss() it.
Â
page.on(‘dialog’, dialog => dialog.accept());
await page.getByRole(‘button’).click();
Note :Â
page.on(‘dialog’) listener must handle the dialog. Otherwise your action will stall, be it locator.click() or something else. That’s because dialogs in Web are modals and therefore block further page execution until they are handled.
Â
As a result, the following snippet will never resolve:
Â
page.on(‘dialog’, dialog => console.log(dialog.message()));
await page.getByRole(‘button’).click(); // Will hang here
Â
Note :Â
If there is no listener for page.on(‘dialog’), all dialogs are automatically dismissed.
beforeunload dialog
When page.close() is called with the truthy runBeforeUnload parameter, the page executes its unload handlers. This is the sole instance in which page.close() does not pause for the page to fully close, as it is possible for the page to remain open at the conclusion of the operation.
Â
You have the option to register a dialog handler to manage the beforeunload dialog on your own:
Â
page.on(‘dialog’, async dialog => {
  assert(dialog.type() === ‘beforeunload’);
  await dialog.dismiss();
});
await page.close({ runBeforeUnload: true });
Print dialogs
To confirm that a print dialog was initiated through window.print, you may utilize the following code snippet:
Â
await page.goto(‘<url>’);
Â
await page.evaluate(‘(() => {window.waitForPrintDialog = new Promise(f => window.print = f);})()’);
await page.getByText(‘Print it!’).click();
Â
await page.waitForFunction(‘window.waitForPrintDialog’);
Â
This will pause until the print dialog is displayed following the button click. Ensure that you assess the script prior to clicking the button or after the page has fully loaded.
Playwright Essentials: A Step-by-Step Journey into Test Automation
Part 01: Master Playwright Testing – Framework from Scratch Guide
Part 02: How to install Playwright
Part 03: Basic Playwright Test Structure
Part 04: Importance of Playwright configuration file and its details to run the tests
Part 05: Writing Tests in PlayWright
Part 06: Playwright Actions Illustrated
Part 07: Auto-waiting