How to output debug information from puppeteer page context

I’m working with puppeteer and running into issues trying to debug my code. When I’m inside the page.evaluate() function, I can’t see any output from my variables or strings. Regular console.log statements don’t show up in my terminal.

Here’s what I’m trying to do:

const puppeteer = require('puppeteer');
const browser = await puppeteer.launch({headless: 'new'});
const tab = await browser.newPage();
await tab.goto(myURL);

await tab.evaluate(() => {
    let myVariable = 'hello world';
    // I want to see this variable's value somehow
    // Normal console.log doesn't work here
});

What’s the best way to get visibility into what’s happening inside the evaluate function? I need to see the values of my variables and strings for debugging purposes.

Another trick: use page.exposeFunction() to create a custom logging function that bridges browser and node contexts. Add await page.exposeFunction('myLog', (...args) => console.log(...args)); before your evaluate call, then use myLog() inside evaluate instead of console.log. Works great for complex debugging.

Your page.evaluate() runs within the browser context, which is why standard console.log statements don’t appear in your terminal. To enable visibility into your browser’s console messages, you can add a listener right after creating your page: tab.on('console', msg => console.log('PAGE LOG:', msg.text()));. This will log all console messages from the browser to your Node.js terminal. Alternatively, you can return values directly from the evaluate function and log them in your Node.js environment for debugging. The console event listener is particularly useful for capturing all messages seamlessly.

You can also use the browser’s developer tools directly - just set headless: false and add devtools: true in your launch options. This opens the browser window with DevTools so you can see console output in real-time. Drop debugger; statements inside your evaluate function to pause execution and inspect variables manually. For automated debugging, try page.evaluateHandle() instead of page.evaluate() when you need to inspect complex objects. It returns a handle you can work with from your Node.js code. This works great for DOM elements or objects that don’t serialize well.