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
| Type | Is it real DOM? | How to handle in Playwright | Key API |
|---|---|---|---|
alert() | No (browser-native) | page.on('dialog', d => d.accept()) before click | dialog.message(), accept() |
confirm() | No | Register handler, then accept() (OK) or dismiss() (Cancel) | accept() / dismiss() |
prompt() | No | Pass text: d.accept('value') | defaultValue(), accept(text) |
beforeunload | No | Check d.type()==='beforeunload'; page.close({runBeforeUnload:true}) | dialog.type() |
HTML <dialog> | Yes | Normal locators; assert visibility & returnValue | getByRole('dialog') |
| Custom modal (div) | Yes | Locate by role/testid; web-first toBeVisible() | expect(loc).toBeVisible() |
| Toast / snackbar | Yes (transient) | Assert visible, then hidden; no hard sleeps | toBeVisible() / toBeHidden() |
⭐ Golden rule: register page.on('dialog', …) before the action that triggers a native dialog — otherwise it auto-dismisses and your handler never runs.