在Puppeteer中的main和renderer函数之间进行通信 [英] Communicating between the main and renderer function in Puppeteer
问题描述
有没有办法在Puppeteer中的主要和渲染器进程之间进行通信,类似于 ipcMain 和 ipcRenderer 在电子。
Is there a way to communicate between the main and renderer process in Puppeteer similar to the ipcMain and ipcRenderer functions in Electron.
这个发布。我发现通过从页面
触发事件到主函数,反之亦然,这个功能可用于调试。
A simple application is demonstrated in this post. I find this functionality can be useful for debugging by triggering event from the page
to the main function and vice-versa.
推荐答案
调试:
- Puppeteer有各种用于调试目的的页面事件这里。
- Puppeteer最近添加了ASYNC堆栈跟踪,以便您可以更准确地跟踪错误。
Debugging: - Puppeteer has various page events used for debugging purpose here. - Puppeteer recently added ASYNC stack trace so you can track errors more precisely.
事件发生,
您可以使用默认的事件
模块和 exposeFunction
构建您自己的事件系统。
Event emitting,
You can use the default events
module and exposeFunction
to build your own events system.
请参阅以下具有所有上述方法的代码段,
Refer to the following code snippet that has all of the mentioned methods,
const EventEmitter = require("events");
const myEventTracker = new EventEmitter();
myEventTracker.on("some-event", function(...data) {
// do something on event
console.log(data);
});
// usage in puppeteer
const puppeteer = require("puppeteer");
puppeteer.launch({ headless: false }).then(async browser => {
const page = await browser.newPage();
// normal console events forwarded to node context
page.on("console", msg => console.log(msg.text()));
// we can use this to make our own reverse events
myEventTracker.on("change-viewport", async function(data) {
// do something on event
await page.setViewport({ width: data.width, height: data.height });
});
// or we can expose the emit function
await page.exposeFunction("emitter", (...data) =>
myEventTracker.emit(...data)
);
// emit however we want
await page.evaluate(async => {
emitter("change-viewport", { width: 1200, height: 800 });
emitter("some-event", "inside browser");
});
await page.goto("http://viewportsizes.com/mine/");
// await browser.close();
});
如果我们要解释所有内容,它将成为博客文章,否则我将更新我的答案。
It will become a blog post if we want to explain all, I will update my answer otherwise.
这篇关于在Puppeteer中的main和renderer函数之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!