对话框
介绍
🌐 Introduction
Playwright 可以与网页对话框进行交互,例如 alert、confirm、prompt 以及 beforeunload 确认框。有关打印对话框,请参见 Print。
🌐 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.AcceptAsync() 或 Dialog.DismissAsync() 来处理它。
🌐 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();
Page.Dialog 监听器必须处理对话框。否则你的操作将会暂停,无论是 Locator.ClickAsync() 还是其他操作。这是因为网页中的对话框是模态的,因此在它们被处理之前会阻塞页面的进一步执行。
因此,以下代码片段将永远无法解析:
🌐 As a result, the following snippet will never resolve:
错误!
🌐 WRONG!
page.Dialog += (_, dialog) => Console.WriteLine(dialog.Message);
await page.GetByRole(AriaRole.Button).ClickAsync(); // Will hang here
如果没有 Page.Dialog 的监听器,所有对话框将自动关闭。
卸载前对话框
🌐 beforeunload dialog
当以为真值的 RunBeforeUnload 调用 Page.CloseAsync() 时,页面会运行其卸载处理程序。这是唯一一种 Page.CloseAsync() 不会等待页面实际关闭的情况,因为操作结束时页面可能仍然保持打开状态。
🌐 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.
你可以注册一个对话处理程序来自行处理 beforeunload 对话:
🌐 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 });
打印对话框
🌐 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.GotoAsync("<url>");
await Page.EvaluateAsync("(() => {window.waitForPrintDialog = new Promise(f => window.print = f);})()");
await Page.GetByText("Print it!").ClickAsync();
await Page.WaitForFunctionAsync("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.