Version: 1.10.0

Dialogs

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 accept or decline it.

page.onDialog(dialog -> dialog.accept());
page.click("button");
note

Page.onDialog(handler) listener must handle the dialog. Otherwise your action will stall, be it Page.click(selector[, options]), Page.evaluate(expression[, arg]) or any other. That's because dialogs in Web are modal and block further page execution until they are handled.

As a result, following snippet will never resolve:

warning

WRONG!

page.onDialog(dialog -> System.out.println(dialog.message()));
page.click("button"); // Will hang here
note

If there is no listener for Page.onDialog(handler), all dialogs are automatically dismissed.

API reference#

beforeunload dialog#

When Page.close([options]) is invoked with the truthy runBeforeUnload value, it page runs its unload handlers. This is the only case when Page.close([options]) 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.onDialog(dialog -> {
assertEquals("beforeunload", dialog.type());
dialog.dismiss();
});
page.close(new Page.CloseOptions().setRunBeforeUnload(true));