如何在 puppeteer 中检测警报

How to detect a alert in puppeteer

如何检测导航后页面是否显示带有某些消息的警报。

puppeteer 可以检测或识别页面是否显示警告框。

我试过了

page.on('popup', ()=> {
   console.log('popup detected');
});

另外,

page.on('dialog', ()=> {
   console.log('popup detected');
});

如评论中所述:如果您在调用 page.goto 之后注册事件处理程序(您的代码),则在您监听事件之前,该事件已经被触发。

因此,请务必在代码后调用 page.goto

这是我的两分钱:

 private async gotoPage(path):Promise<Response|Result> {
        return new Promise(async(resolve, reject) => {
            await Promise.all([
                this.page.on('dialog', async (dialog) => {
                    await dialog.dismiss().catch(() => {
                        console.log(dialog.message());
                        return new Result(TestStatus.FAIL, dialog.message());
                    });
                }),
                this.page.goto(`${this.baseURL}${path}`),
                this.page.waitForNavigation({ waitUntil: 'load' })]).then(
                async () => {
                    resolve(new Result(TestStatus.PASS, `Loading to path success : ${path}`));
                },
                async () => {
                    reject(new Result(TestStatus.FAIL, `Could not GotoPage : ${path}`));
                });
        });
    }