Skip to content

Alerts / Dialogs — Playwright Practice

1. Native alert() / confirm() / prompt()Beginner Intermediate

Greeting will appear here…
  • Handle simple alert and delayed alert.
  • Check type, message of simple alert and delayed alert.
  • Handle confirm alert; check type, message, defaultValue.
  • Handle prompt alert; check type, message, defaultValue, then provide input text.
  • Assert result text after accepting or dismissing confirm/prompt.

2. beforeunload — leave-page warningAdvanced

State: clean (no warning)

  • Handle before unload alert.
  • Enter text then try to reload / navigate away.
  • Check alert type, message, defaultValue, then provide input text.
  • Assert text value after accepting or dismissing.

3. Toast / Snackbar (auto-dismiss)Advanced

Appears then disappears after ~3s — a classic flaky-test trap.

  • Handle toast which appear for 3sec then disapper.
  • Check alert type, message, defaultValue, then provide input text.
  • Assert text value before disappearing.
  • Assert with web-first toBeVisible() immediately, then toBeHidden() after 3s. without hardcoding wait.

4. Dialog Handling Cheat Sheet

TypeIs it real DOM?How to handle in PlaywrightKey API
alert()No (browser-native)page.on('dialog', d => d.accept()) before clickdialog.message(), accept()
confirm()NoRegister handler, then accept() (OK) or dismiss() (Cancel)accept() / dismiss()
prompt()NoPass text: d.accept('value')defaultValue(), accept(text)
beforeunloadNoCheck d.type()==='beforeunload'; page.close({runBeforeUnload:true})dialog.type()
HTML <dialog>YesNormal locators; assert visibility & returnValuegetByRole('dialog')
Custom modal (div)YesLocate by role/testid; web-first toBeVisible()expect(loc).toBeVisible()
Toast / snackbarYes (transient)Assert visible, then hidden; no hard sleepstoBeVisible() / toBeHidden()

⭐ Golden rule: register page.on('dialog', …) before the action that triggers a native dialog — otherwise it auto-dismisses and your handler never runs.