首页 > 解决方案 > 在 Puppeteer 中如何在控制台中捕获 Chrome 浏览器日志

问题描述

我正在尝试收集 Chrome 浏览器日志:浏览器发出的警告,例如弃用和干预。例如,对于站点https://uriyaa.wixsite.com/corvid-cli2

A cookie associated with a cross-site resource at http://wix.com/ was set without the `SameSite` attribute.
A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`.
You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.

我认为下面的代码可以解决问题,但它只捕获页面代码生成的日志。

(async ()=> {
    const browser = await puppeteer.launch({dumpio: true});
    const page = await browser.newPage();
    page.on('console', msg => {
        for (let i = 0; i < msg._args.length; ++i)
            console.log(`${i}: ${msg._args[i]}`);
    });
    await page.goto('https://uriyaa.wixsite.com/corvid-cli2', {waitUntil: 'networkidle2', timeout: 20000});
    await page.screenshot({path: 'screenshot.png'});
    await browser.close();
})();

波纹管是不相关的,因为我认为reportingobserver 没有在没有sameSite 的情况下捕获cookie 上的chrome 信息:阅读该主题导致我访问https://developers.google.com/web/updates/2018/07/reportingobserver但我不知道如何使用它,使用浏览器控制台中的示例不起作用。

我不确定应该在哪个上下文中使用观察者代码,或者浏览器是否需要一个标志来激活报告 API。或者,如果这是解决问题的方法。

欢迎帮助。

标签: google-chromegoogle-chrome-devtoolspuppeteer

解决方案


据推测,该'console'事件仅捕获console.log()来自页面的类似调用。但似乎您可以通过CDPSession使用Log Domain从浏览器中捕获警告。不幸的是,它只对我有用的浏览器:

'use strict';

const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch({ headless: false });
    const [page] = await browser.pages();
    const cdp = await page.target().createCDPSession();

    await cdp.send('Log.enable');

    cdp.on('Log.entryAdded', async ({ entry }) => {
      console.log(entry);
    });

    await page.goto('https://uriyaa.wixsite.com/corvid-cli2');
  } catch (err) {
    console.error(err);
  }
})();

其中一项:

{
  source: 'other',
  level: 'warning',
  text: 'A cookie associated with a cross-site resource at http://www.wix.com/ was set without the `SameSite` attribute. It has been blocked, as Chrome now only delivers cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.',
  timestamp: 1589058118372.802,
  url: 'https://uriyaa.wixsite.com/corvid-cli2'
}

推荐阅读