跳至主要内容

对话框

简介

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

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

默认情况下,对话框会被Playwright自动关闭,因此您无需手动处理。不过,您可以在触发对话框的操作之前注册一个对话框处理程序,选择dialog.accept()接受或dialog.dismiss()关闭它。

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

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

因此,以下代码片段将永远不会解析完成:

warning

错误!

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

如果没有为page.on('dialog')设置监听器,所有对话框将自动被关闭。

beforeunload 对话框

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

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

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

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

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

这将等待点击按钮后打印对话框打开。请确保在点击按钮前/页面加载后执行脚本。