Ok, I discovered a built-in way to do this in Puppeteer . Puppeteer defines an exposeFunction method.
page.exposeFunction(name, puppeteerFunction)
This method defines the function with the given name in the window object on the page. The async function on the page side. When it is called, the puppeteerFunction that you define is executed as a callback with the same arguments. The arguments are not JSON-serialized, but passed as JSHandles , so they themselves expose the objects. Personally, I chose JSON serialization of values ββbefore sending them.
I looked at the code and it actually just works by sending console messages, as in the Pasi response, which ignore the Puppeteer console consoles. However, if you are listening to the console directly (i.e. via the stdout pipeline). You will still see them along with regular messages.
Since console information is actually sent by WebSocket, it is pretty efficient. I was a bit opposed to using it, because in most processes the console passes data through stdout, which have problems.
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 javascript page:
window.callPuppeteer(JSON.stringify({ thisCameFromThePage : "hello!" }));
source share