如何通过无头Chrome Runtime.evaluate在终端中获取console.log输出 [英] How to get console.log output in Terminal via Headless Chrome Runtime.evaluate

查看:672
本文介绍了如何通过无头Chrome Runtime.evaluate在终端中获取console.log输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里关注此问题:

https://github.com/cyrus-and/chrome- remote-interface/issues/105

但是我似乎无法在Mac Terminal中获得console.log输出.它可能在我看不到的Chrome Devtools窗口中.

那我如何通过Runtime.evaluate表达式在Mac Terminal中获得console.log输出?

我的下面的代码:

const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');
const file = require('fs');

(async function() {
  async function launchChrome() {
    return await chromeLauncher.launch({
      chromeFlags: [
        '--headless',
        '--disable-gpu'
      ]
    });
  }
  const chrome = await launchChrome();
  const protocol = await CDP({
    port: chrome.port
  });

  const {
    DOM,
    Network,
    Page,
    Emulation,
    Runtime
  } = protocol;

  await Promise.all([Network.enable(), Page.enable(), Runtime.enable(), DOM.enable()]);

  Page.navigate({url: 'https://www.chromestatus.com/'});

  Page.loadEventFired(async () => {
    const result = await Runtime.evaluate({expression: 'console.log(\'aaa\')'});

    protocol.close();
    chrome.kill(); 
  });

})();

解决方案

我一直在对此进行一些研究;以下是我的一些发现:

评估时:

const result = await Runtime.evaluate({ expression: 'console.log("aaa")' });

结果始终为:

{结果:{类型:'undefined'}}

但是,以下表达式:

const result = await Runtime.evaluate({expression: 'window.location.toString()'});

返回:

{结果:{类型:字符串", 值:' https://www.chromestatus.com/features '}}

现在,如果我在不调用函数的情况下评估了函数:

const result = await Runtime.evaluate({ expression: 'console.log' });

结果设置为:

{结果:{类型:功能", className:'功能', 说明:"function log(){[native code]}", objectId:'{"injectedScriptId":2,"id":1}'}}

因此,我做了一些进一步的挖掘,发现每次评估时调用console.log时,总是会触发 Console 对象上的 messageAdded 事件.

因此,我继续并启用了Console对象,并向messageAdded事件添加了一个侦听器,现在我可以按预期成功捕获控制台条目.

这就是我所做的:

const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');
const file = require('fs');

(async function() {
  async function launchChrome() {
    return await chromeLauncher.launch({
      chromeFlags: [
        '--headless',
        '--disable-gpu'
      ]
    });
  }
  const chrome = await launchChrome();
  const protocol = await CDP({
    port: chrome.port
  });

  const {
    DOM,
    Network,
    Page,
    Emulation,
    Runtime,
    Console
  } = protocol;

  await Promise.all([Network.enable(), Page.enable(), DOM.enable(), Runtime.enable(), Console.enable()]);

  await Page.navigate({url: 'https://www.chromestatus.com/'});

  // REMARKS: messageAdded is fired every time a new console message is added
  Console.messageAdded((result) => {
    console.log(result);
  });

  Page.loadEventFired(async () => {
    const result = await Runtime.evaluate({ expression: 'console.log("aaa")' });

    // REMARKS: When evaluating console.log, result.result.value is undefined.
    console.log(result);

    protocol.close();
    chrome.kill(); 
  });

})();

/* Output from listening on messageAdded:
{ message: 
   { source: 'console-api',
     level: 'log',
     text: 'aaa',
     url: '',
     line: 1,
     column: 9 } }
*/

我从 Chrome DevTools协议查看器-控制台

从文档中:

Console.messageAdded

添加新的控制台消息时发出.

希望这会有所帮助!

I am following this issue post here:

https://github.com/cyrus-and/chrome-remote-interface/issues/105

But I cannot seem to get console.log output in the Mac Terminal. It's probably inside the Chrome Devtools window which I don't see.

So how do I get console.log output in Mac Terminal via Runtime.evaluate expression?

My code below:

const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');
const file = require('fs');

(async function() {
  async function launchChrome() {
    return await chromeLauncher.launch({
      chromeFlags: [
        '--headless',
        '--disable-gpu'
      ]
    });
  }
  const chrome = await launchChrome();
  const protocol = await CDP({
    port: chrome.port
  });

  const {
    DOM,
    Network,
    Page,
    Emulation,
    Runtime
  } = protocol;

  await Promise.all([Network.enable(), Page.enable(), Runtime.enable(), DOM.enable()]);

  Page.navigate({url: 'https://www.chromestatus.com/'});

  Page.loadEventFired(async () => {
    const result = await Runtime.evaluate({expression: 'console.log(\'aaa\')'});

    protocol.close();
    chrome.kill(); 
  });

})();

解决方案

I've been doing some research on this; below are some of my findings:

When evaluating:

const result = await Runtime.evaluate({ expression: 'console.log("aaa")' });

Result is always:

{ result: { type: 'undefined' } }

However, the following expression:

const result = await Runtime.evaluate({expression: 'window.location.toString()'});

Returns:

{ result: { type: 'string', value: 'https://www.chromestatus.com/features' } }

Now if I evaluate the function without invoking it:

const result = await Runtime.evaluate({ expression: 'console.log' });

Result is set to:

{ result: { type: 'function', className: 'Function', description: 'function log() { [native code] }', objectId: '{"injectedScriptId":2,"id":1}' } }

So I did some more digging, and found that every time console.log is invoked when evaluated, the messageAdded event on the Console object is always fired.

So I went ahead and enabled the Console object and added a listener to the messageAdded event, and now I can successfully capture the console entry as expected.

This is what I did:

const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');
const file = require('fs');

(async function() {
  async function launchChrome() {
    return await chromeLauncher.launch({
      chromeFlags: [
        '--headless',
        '--disable-gpu'
      ]
    });
  }
  const chrome = await launchChrome();
  const protocol = await CDP({
    port: chrome.port
  });

  const {
    DOM,
    Network,
    Page,
    Emulation,
    Runtime,
    Console
  } = protocol;

  await Promise.all([Network.enable(), Page.enable(), DOM.enable(), Runtime.enable(), Console.enable()]);

  await Page.navigate({url: 'https://www.chromestatus.com/'});

  // REMARKS: messageAdded is fired every time a new console message is added
  Console.messageAdded((result) => {
    console.log(result);
  });

  Page.loadEventFired(async () => {
    const result = await Runtime.evaluate({ expression: 'console.log("aaa")' });

    // REMARKS: When evaluating console.log, result.result.value is undefined.
    console.log(result);

    protocol.close();
    chrome.kill(); 
  });

})();

/* Output from listening on messageAdded:
{ message: 
   { source: 'console-api',
     level: 'log',
     text: 'aaa',
     url: '',
     line: 1,
     column: 9 } }
*/

I got the details from Chrome DevTools Protocol Viewer - Console

From the documentation:

Console.messageAdded

Issued when new console message is added.

Hope this helps!

这篇关于如何通过无头Chrome Runtime.evaluate在终端中获取console.log输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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