Frames and Files

Dialogs in Playwright

Dialogs in Playwright: definition, handling alert/confirm/prompt Dialogs, examples, mistakes, interview notes, and practice.

Definition and Brief Explanation

Definition: Dialogs in Playwright are browser popup messages such as alert, confirm, prompt, and beforeunload Dialogs.

Explanation: Dialogs block the page until they are accepted or dismissed. Playwright tests should register the dialog handler before the action that opens the dialog, otherwise the test can hang or miss the event.

Why It Matters

  • It covers blocking browser dialogs that can freeze a test if not handled.
  • It verifies alert, confirm, and prompt behavior from the user perspective.
  • It allows tests to accept, dismiss, or provide prompt text intentionally.
  • It prevents flaky failures caused by missed dialog events.

How It Works

  1. Register page.on("dialog") or waitForEvent("dialog") before the action.
  2. Trigger the button or event that opens the dialog.
  3. Read the dialog message when needed.
  4. Accept or dismiss the dialog and assert the page result.

Syntax and Examples

Example 1: Accept dialog

page.once('dialog', dialog => dialog.accept());
await page.getByRole('button', { name: 'Delete' }).click();

Explanation: Register the handler before clicking the button that opens the dialog.

Common Mistakes

  • Adding the dialog handler after the dialog opens.
  • Accepting every dialog globally without checking the message.
  • Forgetting prompt text for prompt dialogs.
  • Testing only the dialog and not the page result after it closes.

Interview Notes

  1. Why can dialogs make tests hang?
  2. How do you accept a confirm dialog?
  3. How do you validate a dialog message?
  4. When would you dismiss instead of accept?

Practice Task

Create one alert test and one confirm test. Verify the dialog message and assert the page result after accepting or dismissing it.