What are the methods to pass information between Node.js and Puppeteer scripts?

I have a Node.js app that begins with main.js. This main file opens Puppeteer and puts a script called automation.js into a headless browser page using the addScriptTag method.

Right now I use cookies to send starting data before adding the script, but I want better ways to share information back and forth.

I can think of two options - using cookies or making a socket connection for network communication.

Are there other methods to send and get data between my main.js file and the Puppeteer browser instance? I need something reliable for two-way communication.

I’ve done this before - page.on(‘console’) with console.log() works great for browser-to-Node communication. Going the other way, just use page.evaluateOnNewDocument() to inject variables before your script loads. I also like using localStorage through page.evaluate(). Set data from Node.js, read it in your injected script, then update localStorage from the browser and check it periodically from Node.js. No network overhead and it’s more persistent than evaluate functions. Beats cookies since you get better data types and no size limits.

Try page.evaluateHandle() and page.queryObjects() to keep object references across the boundary. When I built a complex automation system, I created a custom communication layer with page.addInitScript() - worked way better than cookies for setup. Just inject a global object both sides can access. You could also use CDP (Chrome DevTools Protocol) directly through Puppeteer’s client. More control but needs extra setup. For real-time bidirectional communication, I ended up using a simple file-based approach - Node.js writes JSON to temp files and the browser script polls them. Not pretty but super reliable and no network setup like sockets.

you could also use page.evaluate() to run code directly in the browser and pull data back to your Node.js script. or try page.exposeFunction() - it exposes your node.js functions to the browser, which is cleaner than messing with cookies.