I’m building an automation script for a browser game and need help with communication between different levels of code.
Here’s my situation: I can successfully navigate to the site, log in, and reach the game page using Puppeteer. Now I want to inject a script that runs directly on the webpage. This script would use jQuery to monitor the page content and detect specific game states.
The tricky part is getting the injected script to communicate back to my main Puppeteer code. When my page-level script detects certain conditions, I need it to trigger actions in the Node.js environment.
For instance, imagine I have a function that checks the page every second for element Z. Once Z appears, I want to extract some data from element W and pass that information to my Puppeteer script. Then the Puppeteer code should use that data to perform mouse movements or other actions that can only be done from the Node.js side.
What’s the best approach for this kind of bidirectional communication? I’m struggling with the async nature of this setup and would appreciate guidance on the proper way to handle this workflow.
Custom events work great for this. Have your injected script fire custom events on the document when it catches game state changes, then use page.evaluateOnNewDocument() to set up listeners for those events. I’ve done this for tracking dynamic content - handles async stuff nicely without the polling overhead.
Window object approach worked great for me with similar requirements. Your injected script stores data directly on window.gameData or whatever property, then use page.evaluate() from Puppeteer to check that data periodically. For the reverse direction, inject commands into window.commands array and have your page script poll it.
Basically treat the window object as a shared message bus. Your monitoring script writes detection results to specific window properties, Puppeteer reads them during evaluation cycles. No complex async handling - you’re just reading/writing simple object properties.
I poll every 500ms - good balance between responsiveness and performance. Way simpler than function exposure and handles those timing issues naturally.
I ran into this same issue building a trading dashboard. Use page.exposeFunction() to bridge your injected script and Node.js code. Expose a function in your Puppeteer script that receives data from the page. Then your injected script calls this function when it detects whatever you’re monitoring. For sending data back, use page.evaluate() to push commands to your injected script. I set up a simple message queue where the injected script polls for instructions and reports status through the exposed function. Works great since both sides run independently but stay connected.