Skip to main content




Playwright 可以与网页对话框进行交互,例如 alertconfirmprompt 以及 beforeunload 确认。

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

alert(), confirm(), prompt() 对话框

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

默认情况下,对话框会被 Playwright 自动关闭,因此你无需处理它们。但是,你可以在触发 dialog.accept()dialog.dismiss() 对话框的操作之前注册一个对话框处理程序。

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.accept() or dialog.dismiss() it.

page.on('dialog', dialog => dialog.accept());
await page.getByRole('button').click();

page.on('dialog') 监听器必须处理该对话框。否则你的行动将会停滞,无论是 还是其他什么。这是因为 Web 中的对话框是模态的,因此会阻止进一步的页面执行,直到它们被处理为止。

page.on('dialog') listener must handle the dialog. Otherwise your action will stall, be it 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:




page.on('dialog', dialog => console.log(dialog.message()));
await page.getByRole('button').click(); // Will hang here

如果 page.on('dialog') 没有监听器,则所有对话框都会自动关闭。

If there is no listener for page.on('dialog'), all dialogs are automatically dismissed.


beforeunload dialog

当使用真实的 runBeforeUnload 值调用 page.close() 时,页面将运行其卸载处理程序。这是 page.close() 不等待页面实际关闭的唯一情况,因为页面可能在操作结束时保持打开状态。

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

你可以注册一个对话框处理程序来自己处理 beforeunload 对话框:

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

page.on('dialog', async dialog => {
assert(dialog.type() === 'beforeunload');
await dialog.dismiss();
await page.close({ runBeforeUnload: true });