有没有一种方法可以在Puppeteer中的主进程与渲染器进程之间进行通信,类似于Electron中的ipcMain和ipcRenderer函数.
post演示了一个简单的应用程序.我发现通过触发页面到主函数之间的事件,此功能对于调试很有用.
解决方法:
调试:
-Puppeteer具有用于调试目的here的各种页面事件.
-Puppeteer最近发布了added ASYNC stack trace,因此您可以更精确地跟踪错误.
发出事件
您可以使用默认事件模块和暴露函数来构建自己的事件系统.
请参考以下包含所有上述方法的代码段,
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();
});
如果我们要解释所有内容,它将成为博客文章,否则,我将更新我的答案.