Skip to main content

Dialogs

Introduction

Playwright can interact with the web page dialogs such as alert, confirm, prompt as well as beforeunload confirmation.

alert(), confirm(), prompt() dialogs

By default, dialogs are auto-dismissed by Playwright, so you don't have to handle them. However, you can register a dialog handler before the action that triggers the dialog to either Dialog.AcceptAsync() or Dialog.DismissAsync() it.

Page.Dialog += async (_, dialog) =>
{
await dialog.AcceptAsync();
};
await Page.GetByRole(AriaRole.Button).ClickAsync();
note

Page.Dialog listener must handle the dialog. Otherwise your action will stall, be it Locator.ClickAsync() or something else. That's because dialogs in Web are modals and therefore block further page execution until they are handled.

As a result, the following snippet will never resolve:

warning

WRONG!

page.Dialog += (_, dialog) => Console.WriteLine(dialog.Message);
await page.GetByRole(AriaRole.Button).ClickAsync(); // Will hang here
note

If there is no listener for Page.Dialog, all dialogs are automatically dismissed.

beforeunload dialog

When Page.CloseAsync() is invoked with the truthy runBeforeUnload value, the page runs its unload handlers. This is the only case when Page.CloseAsync() does not wait for the page to actually close, because it might be that the page stays open in the end of the operation.

You can register a dialog handler to handle the beforeunload dialog yourself:

Page.Dialog += async (_, dialog) =>
{
Assert.AreEqual("beforeunload", dialog.Type);
await dialog.DismissAsync();
};
await Page.CloseAsync(new() { RunBeforeUnload = true });