Skip to main content
The Dialog class represents JavaScript dialogs created by alert(), confirm(), prompt(), or beforeunload events. Playwright automatically dismisses dialogs unless you explicitly handle them.

Overview

Methods

type()

Get the type of the dialog. Returns: string Possible values:
  • 'alert'
  • 'beforeunload'
  • 'confirm'
  • 'prompt'

message()

Get the message displayed in the dialog. Returns: string

defaultValue()

Get the default value for prompt dialogs. Returns: string Returns an empty string for non-prompt dialogs:

accept(promptText?)

Accept the dialog. For prompt dialogs, optionally provide input text.
string
Text to enter in prompt dialog (only for prompt type)
Returns: Promise<void>

dismiss()

Dismiss the dialog (click Cancel). Returns: Promise<void>

page()

Get the page that opened the dialog. Returns: Page | null Returns null if the dialog was opened during page initialization:

Examples

Handle Alert Dialog

Handle Confirm Dialog

Handle Prompt Dialog

Conditional Dialog Handling

Wait for Specific Dialog

Handle BeforeUnload Dialog

Collect All Dialogs

Best Practices

Always Handle Dialogs

Unhandled dialogs will cause tests to hang:

Use Once for Single Dialogs

If you expect only one dialog:

Handle Dialogs Before Triggering

Set up the handler before the action that triggers the dialog:

Clean Up Event Listeners

Remove listeners when they’re no longer needed:

Common Pitfalls

Missing Dialog Handler

If a dialog appears without a handler, the test will timeout:

Async Handler Issues

Dialog handlers should not perform long async operations: