使用Puppeteer无头运行来捕获崩溃事件

时间:2018-07-05 17:57:33

标签: javascript puppeteer

有没有办法在无头模式下使用Puppeteer捕获铬页面崩溃事件?

仅在非无头模式下,以下内容有效吗?:

page.once("error", async () => {
   //Do something
});

await page.goto('about:crash');

我正在使用无头参数来启动操纵up。 (以保持激活WebGL)

browser = await puppeteer.launch({
    headless: false,
    args: [
        `--window-size=${width},${height}`,
        '--headless'
    ]
}); 

添加的详细信息: 我的目标是在崩溃后测试我的应用行为。

以下内容未捕获该错误:

const puppeteer = require('puppeteer');

const width = 1920;
const height = 1080;

(async () => {
    browser = await puppeteer.launch({
        headless: false,
        args: [
            `--window-size=${width},${height}`,
            '--headless'
        ]
    });

    page = await browser.newPage();
    await page.goto('https://www.google.com/', { waitUntil: 'networkidle2', timeout: 10000 });
    console.log('page loaded');

    try {
        //page.goto('about:crash');
        page.goto('chrome://crash/')

    } catch (e) {
        console.log(`crash has been catched`)
    };
})();

这确实可以,但是我得到了诺言拒绝,这使我的Jest测试失败了

const puppeteer = require('puppeteer');

const width = 1920;
const height = 1080;

(async () => {
    browser = await puppeteer.launch({
        headless: false,
        args: [
            `--window-size=${width},${height}`,
            '--headless'
        ]
    });

    page = await browser.newPage();
    await page.goto('https://www.google.com/', { waitUntil: 'networkidle2', timeout: 10000 });
    console.log('page loaded');

    page.once("error", async () => {
        console.log('crash has been catched')
    })

    //page.goto('about:crash');
    page.goto('chrome://crash/')

})();

我怎么

  1. 崩溃页面,
  2. 捕获崩溃错误
  3. 再做一些测试(例如 创建新页面,重新加载页面...)

1 个答案:

答案 0 :(得分:0)

您可以使用try / catch。您还可以设置bool变量来知道何时关闭/打开新页面。 (例如reusePageInstance)

这里是一个示例:

const puppeteer = require('puppeteer');

var reusePageInstance = true;

(async() => {
  const args = [
    "--disable-setuid-sandbox",
    "--no-sandbox",
  ];
  const options = {
    args,
    headless: true,
    ignoreHTTPSErrors: true,
  };

  const browser = await puppeteer.launch(options);

  let page

  if (!reusePageInstance) {
    page = await browser.newPage()
  }

  var q = ['http://www.stackoverfllow.com']

  while (q.length > 0) {

    let url = q.shift()
    console.log('Loading Page: ' +' - ' + url)

    try {
      if (reusePageInstance) {
        page = await browser.newPage()
      }

      await page.goto(url, {
        timeout: 10000,
        waitUntil: 'networkidle2'
      })
      console.log('Page Loaded')

      const html = await page.content();
      // do something

      if (reusePageInstance) {
        await page.close()
      }
      console.log('Page closed')
    } catch (e) {
      console.log('**** FAIL ****')
      console.log('Page Load Failed', url)
      console.error(e)
      await page.close()
    }
  }
  await browser.close()

})()