Displaying console output from Puppeteer's page.evaluate in Node.js

Hey everyone! I’m working on a Puppeteer project and I’m stuck. Does anyone know how to show console logs from inside the page.evaluate function? I want to see these logs in my Node.js environment while the page is being evaluated.

The main thing is I need to keep track of what’s happening during the evaluation process. It would be great if I could show some progress updates or results to the user as the script runs.

I’ve tried a few things but can’t seem to get it working. Any ideas or tips would be super helpful! Thanks in advance for your help.

yo, have u tried using the page.exposeFunction() method? it lets u create a function in node that the browser can call. u could make a ‘log’ function that prints to node’s console, then use it in page.evaluate like this: await page.evaluate(() => log(‘hey from the browser!’)). might be worth a shot!

I’ve faced similar challenges with Puppeteer, and here’s what worked for me. Instead of relying solely on console.log, I implemented a custom logging mechanism using page.evaluate() in combination with page.exposeFunction().

Here’s the gist:

  1. Define a custom log function in your Node.js environment.
  2. Expose this function to the browser context using page.exposeFunction().
  3. Use the exposed function within page.evaluate() to send logs back to Node.js.

This approach gives you more control over how logs are handled and displayed. You can even add timestamps or log levels if needed. It’s been a game-changer for tracking progress and debugging complex Puppeteer scripts.

Remember to clean up any listeners or exposed functions when you’re done to avoid memory leaks. Hope this helps!

To display console output from page.evaluate in Node.js, use the page.on(‘console’) event listener. First, set up the listener before calling page.evaluate by adding code such as page.on(‘console’, msg => console.log(‘Page log:’, msg.text())). Then, within page.evaluate, use console.log as you normally would, for example, await page.evaluate(() => { console.log(‘This will be visible in Node.js’); }). This approach captures all console messages from the browser context and relays them to your Node.js environment, which is especially useful for debugging and providing progress updates during script execution. Be sure to handle different console message types like error or warn for more detailed logging.