Communicate “out” from Chromium via DevTools protocol

三世轮回 提交于 2019-12-05 05:52:25

If the script sends all its data back in one call, the simplest approach would be to use page.evaluate and return a Promise from it:

const dataBack = page.evaluate(`new Promise((resolve, reject) => {                                                  
  setTimeout(() => resolve('some data'), 1000)                                                                      
})`)
dataBack.then(value => { console.log('got data back', value) })

This could be generalized to sending data back twice, etc. For sending back an arbitrary stream of events, perhaps console.log would be slightly less of a hack than DOM events? At least it's super-easy to do with Puppeteer:

page.on('console', message => {
  if (message.text.startsWith('dataFromMyScript')) {
    message.args[1].jsonValue().then(value => console.log('got data back', value))
  }
})
page.evaluate(`setInterval(() => console.log('dataFromMyScript', {ts: Date.now()}), 1000)`)

(The example uses a magic prefix to distinguish these log messages from all others.)

Okay, I've discovered a built-in way to do this in Puppeteer. Puppeteer defines a method called exposeFunction.

page.exposeFunction(name, puppeteerFunction)

This method defines a function with the given name on the window object of the page. The function is async on the page's side. When it's called, the puppeteerFunction you define is executed as a callback, with the same arguments. The arguments aren't JSON-serialized, but passed as JSHandles so they expose the objects themselves. Personally, I chose to JSON-serialize the values before sending them.

I've looked at the code, and it actually just works by sending console messages, just like in Pasi's answer, which the Puppeteer console hooks ignore. However, if you listen to the console directly (i.e. by piping stdout). You'll still see them, along with the regular messages.

Since the console information is actually sent by WebSocket, it's pretty efficient. I was a bit averse to using it because in most processes, the console transfers data via stdout which has issues.

Example

Node

async function example() {
    const puppeteer = require("puppeteer");
    let browser = await puppeteer.launch({
        //arguments
    });
    let page = await browser.newPage();

    await page.exposeFunction("callPuppeteer", function(data) {
        console.log("Node receives some data!", data);
    });

    await page.goto("http://www.example.com/target");
}

Page

Inside the page's javascript:

window.callPuppeteer(JSON.stringify({
    thisCameFromThePage : "hello!"
}));

Update: DevTools protocol support

There is DevTools protocol support for something like puppeteer.exposeFunction.

https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-addBinding

If executionContextId is empty, adds binding with the given name on the global objects of all inspected contexts, including those created later, bindings survive reloads. If executionContextId is specified, adds binding only on global object of given execution context. Binding function takes exactly one argument, this argument should be string, in case of any other input, function throws an exception. Each binding function call produces Runtime.bindingCalled notification.

.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!