JavaScript Dialogs
The browser's own alert, confirm and prompt boxes, and the "Leave site?" warning. They are not part of the page, so you handle them with events, not locators.
Register the handler first
A native dialog blocks the page until someone answers it. You cannot click it: listen for the dialog event before the action that opens it, then accept or dismiss it.
page.once('dialog', async (dialog) => {
expect(dialog.message()).toBe('Do you want to continue?');
await dialog.accept(); // or dialog.dismiss()
});
await page.getByRole('button', { name: 'Confirm' }).click();false and the app quietly takes the "Cancel" path. Your test still passes, unless you assert the result.Prompts
dialog.accept('Ada') types an answer. dialog.accept() with no text answers with an empty string, not the pre-filled value. That one is in dialog.defaultValue().
More than one dialog
page.once() handles only the next dialog. When an action opens several, use page.on() and decide by dialog.type(), then remove the handler with page.off().
const handler = async (dialog: Dialog) => {
if (dialog.type() === 'confirm') await dialog.accept();
else if (dialog.type() === 'prompt') await dialog.accept('DELETE');
};
page.on('dialog', handler);
await page.getByRole('button', { name: 'Delete account' }).click();
page.off('dialog', handler);Waiting for a dialog
If you need the dialog itself, wait for the event. Start waiting before the action, as with downloads and popups.
const dialogPromise = page.waitForEvent('dialog');
await page.getByRole('button', { name: 'Start session' }).click();
const dialog = await dialogPromise;
await dialog.accept();"Leave site?"
A beforeunload warning has the type beforeunload. Playwright skips these handlers when it closes a page, unless you ask for them:
page.once('dialog', (dialog) => dialog.dismiss()); // stay on the page
await page.close({ runBeforeUnload: true });Alert, confirm and prompt
Delete a file
Every delete asks for confirmation first.
- report.pdf
- budget.xlsx
- notes.txt
Two dialogs in a row
Deleting the account asks twice: a confirm, then a prompt.
A dialog on a delay
Two seconds after you start, the session warns that it is about to expire.
Unsaved changes
Type a note, then try to reload or close the tab before saving.
All changes saved
Related exercises
- Dialogs & WindowsIntermediateModals & OverlaysTest modals built into the page: native and custom, stacked, and one that interrupts you.
- FramesAdvancedEmbedded WidgetsTest embedded widgets the way real apps use them.
- Dialogs & WindowsAdvancedTabs & WindowsWork with several pages at once: new tabs, popups, a sign-in window and tabs that share storage.
Read the guide: Playwright practice for beginners: a four-week plan