Playwright Dialogs and Alerts
A fire alarm interrupts every activity in a building until someone acknowledges it. A browser's native alert box behaves similarly, freezing normal page interaction until a person clicks either "OK" or "Cancel." Playwright needs a specific technique to handle these interruptions correctly.
A Dialog Interrupting the Page
Test Clicks "Delete Account"
|
v
Browser Shows a Confirmation Alert
|
v
Page Interaction Pauses Completely
|
v
Test Must Accept or Dismiss the Alert
|
v
Page Continues Normally
Setting Up a Dialog Listener First
page.on('dialog', async (dialog) => {
console.log(dialog.message());
await dialog.accept();
});
await page.getByRole('button', { name: 'Delete Account' }).click();The listener must be created before the action that triggers the dialog. This code reads the dialog's message, then clicks the equivalent of the "OK" button automatically.
Dismissing a Dialog Instead
page.on('dialog', async (dialog) => {
await dialog.dismiss();
});
await page.getByRole('button', { name: 'Delete Account' }).click();This clicks the equivalent of the "Cancel" button, useful for confirming that canceling a dangerous action leaves the data unchanged.
Handling a Prompt That Needs Text Input
page.on('dialog', async (dialog) => {
await dialog.accept('My Custom Answer');
});
await page.getByRole('button', { name: 'Rename File' }).click();Some dialogs ask for typed text before accepting, such as renaming a file. This code types "My Custom Answer" before clicking the equivalent of "OK."
Checking the Dialog's Message and Type
page.on('dialog', async (dialog) => {
expect(dialog.message()).toContain('Are you sure');
expect(dialog.type()).toBe('confirm');
await dialog.accept();
});This confirms the dialog shows the expected warning text and is genuinely a confirmation type, not an unexpected alert or prompt appearing by mistake.
A Real-World Example
An email client shows a browser confirmation dialog asking "Discard this draft?" when a user tries to close an unsaved email. A test dismisses that dialog to confirm the draft remains saved, then accepts it in a separate test to confirm the draft actually gets discarded.
Why the Listener Order Matters
A dialog appearing without any listener attached can freeze a test indefinitely, since Playwright has no instruction on how to respond to it. Setting up the listener as the very first step, before the triggering click, avoids this problem completely.
Quick Practice Task
Find a website action that triggers a native browser confirmation dialog, such as leaving a page with unsaved changes. Write a test that accepts the dialog and one that dismisses it.
Key Takeaways
- Native browser dialogs pause page interaction until handled directly.
- A dialog listener must exist before the action that triggers the dialog.
- accept and dismiss control whether the dialog confirms or cancels.
- Prompts can receive typed text before the dialog gets accepted.
