Handling native dialogs

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();
With no handler, Playwright dismisses every dialog. A confirm then returns 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 });
Browsers only show this warning after the user has interacted with the page. Type into a field with a real click first.

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