Skip to main content

对话框

介绍

¥Introduction

Playwright 可以与网页对话框进行交互,例如 alertconfirmprompt 以及 beforeunload 确认。对于打印对话框,请参阅 打印

¥Playwright can interact with the web page dialogs such as alert, confirm, prompt as well as beforeunload confirmation. For print dialogs, see Print.

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

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

警告

错误的!

¥WRONG!

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 });

¥Print dialogs

为了断言通过 window.print 触发了打印对话框,你可以使用以下代码片段:

¥In order to assert that a print dialog via window.print was triggered, you can use the following snippet:

await page.goto('<url>');

await page.evaluate('(() => {window.waitForPrintDialog = new Promise(f => window.print = f);})()');
await page.getByText('Print it!').click();

await page.waitForFunction('window.waitForPrintDialog');

这将等待单击按钮后打开打印对话框。请确保在单击按钮之前/页面加载后评估脚本。

¥This will wait for the print dialog to be opened after the button is clicked. Make sure to evaluate the script before clicking the button / after the page is loaded.