在 Puppeteer 中如何在控制台中捕获 Chrome 浏览器日志

In Puppeteer how to capture Chrome browser log in the console

我正在尝试收集 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。或者如果这是解决问题的方法。

欢迎帮助。

据推测,'console' 事件仅捕获来自页面的 console.log() 和类似调用。但似乎您可以通过 CDPSession with 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'
}

当您启动 Puppeteer 浏览器时,在选项对象中,您应该将 dumpio 设置为 true:

await puppeteer.launch({ dumpio: true });

这基本上是“将浏览器进程 stdout 和 stderr 传输到 process.stdout 和 process.stderr”,这意味着它会将浏览器日志重定向到任何主进程、服务器等。你是 运行.

您可以在此处看到启动 Puppeteer 时可以使用的这个启动选项和其他启动选项:https://www.puppeteersharp.com/api/PuppeteerSharp.LaunchOptions.html