Communicating Between The Main And Renderer Function In Puppeteer
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
Solution 1:
Debugging: - Puppeteer has various page events used for debugging purpose here. - Puppeteer recently added ASYNC stack trace so you can track errors more precisely.
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,
constEventEmitter = require("events");
const myEventTracker = newEventEmitter();
myEventTracker.on("some-event", function(...data) {
// do something on eventconsole.log(data);
});
// usage in puppeteerconst 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", asyncfunction(data) {
// do something on eventawait page.setViewport({ width: data.width, height: data.height });
});
// or we can expose the emit functionawait page.exposeFunction("emitter", (...data) =>
myEventTracker.emit(...data)
);
// emit however we wantawait 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.
Post a Comment for "Communicating Between The Main And Renderer Function In Puppeteer"