跳至主要内容

对话框

Dialog 对象由页面通过 page.on('dialog') 事件分发。

使用Dialog类的一个示例:

const { chromium } = require('playwright');  // Or 'firefox' or 'webkit'.

(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
page.on('dialog', async dialog => {
console.log(dialog.message());
await dialog.dismiss();
});
await page.evaluate(() => alert('1'));
await browser.close();
})();
note

对话框会自动关闭,除非存在page.on('dialog')监听器。当监听器存在时,它必须通过dialog.accept()dialog.dismiss()来处理对话框 - 否则页面会冻结等待对话框响应,像点击这样的操作将永远无法完成。


方法

accept

Added before v1.9 dialog.accept

当对话框被接受时返回。

用法

await dialog.accept();
await dialog.accept(promptText);

参数

  • promptText string (可选)#

    要在提示框中输入的文本。如果对话框的type不是prompt类型,则不会产生任何效果。可选参数。

返回


默认值

Added before v1.9 dialog.defaultValue

如果对话框是提示框,则返回默认提示值。否则,返回空字符串。

用法

dialog.defaultValue();

返回


关闭

Added before v1.9 dialog.dismiss

当对话框被关闭时返回。

用法

await dialog.dismiss();

返回


消息

Added before v1.9 dialog.message

对话框中显示的消息。

用法

dialog.message();

返回


页面

Added in: v1.34 dialog.page

触发此对话框的页面(如果存在)。

用法

dialog.page();

返回


类型

Added before v1.9 dialog.type

返回对话框的类型,可以是以下之一:alertbeforeunloadconfirmprompt

用法

dialog.type();

返回