Puppeteer 不拿起对话框 [英] Puppeteer not picking up dialog box

查看:39
本文介绍了Puppeteer 不拿起对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Puppeteer 中测试警报框:

I'm trying to test for an alert box in Puppeteer:

    msg = '';
    await page.goto('http://localhost:8080/', {
      waitUntil: 'networkidle2'
    });
    await page.$eval('#value', el => el.value = '<script>alert("BLEH")</script>');
    page.on('dialog', async dialog => {
      msg = dialog.message();
      await dialog.dismiss()
    })
    // submit comment
    await page.$eval('#message', form => form.submit());
    expect(msg).toEqual('BLEH');

但是,它似乎没有在警报框中返回消息(即使我已经确认它可以手动执行).为什么 page.on('dialog', async dialog => { 没有被输入?

However, it doesn't seem to return the message inside the alert box (even though I've confirmed it works doing it manually). Any ideas why page.on('dialog', async dialog => { isn't being entered?

推荐答案

我不确定你的页面发生了什么——看起来你正在测试 XSS,但无论如何,你可以承诺对话框处理程序解析为本例中的 dialog.message() 值.

I'm not sure what's going on with your page -- it looks like you're testing XSS, but in any case, you can promisify the dialog handler to resolve to the dialog.message() value as in this example.

请注意,我正在使用 Enter 提交表单 -- 调用 form.submit() 似乎覆盖了默认预防措施,杀死了页面,但如果它在您的网站上有效,则该修改不会不改变下面代码的基本点.

Note that I'm submitting the form with Enter -- calling form.submit() seems to override the default prevention, killing the page, but if it works on your site, that modification doesn't change the fundamental point of the code below.

请记住 await dialogDismissed; 永远不会超时,因为它不是 Puppeteer 函数.如果需要,请在承诺中调用 setTimeout(reject, someDelay).

Keep in mind that await dialogDismissed; will never time out since it's not a Puppeteer function. If you want that, call setTimeout(reject, someDelay) in the promise.

const puppeteer = require("puppeteer");

let browser;
(async () => {
  const html = `
    <form id="message"><input id="value"></form>
    <script>
      document
        .getElementById("message")
        .addEventListener("submit", e => {
          e.preventDefault();
          alert(document.getElementById("value").value);
        })
      ;
    </script>
  `;
  browser = await puppeteer.launch();
  const [page] = await browser.pages();
  const dialogDismissed = new Promise((resolve, reject) => {
    const handler = async dialog => {
      await dialog.dismiss();
      resolve(dialog.message());
    };
    page.once("dialog", handler);
  });
  await page.setContent(html);
  const inputEl = await page.$("#value");
  await inputEl.type("hello world");
  await inputEl.press("Enter");
  const msg = await dialogDismissed;
  console.log(msg); // => hello world
  await page.close();
})()
  .catch(err => console.error(err))
  .finally(async () => await browser.close())
;

这篇关于Puppeteer 不拿起对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆