User Agents

Web browsers and everyday web tech, explained

View Console Logs and Errors from Headless Chrome

· 7 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To view console logs and errors from Headless Chrome, you must implement a listener within your automation framework—such as Puppeteer, Playwright, or Selenium—that captures the Chrome DevTools Protocol (CDP) events and redirects them to your local terminal or a log file. Because headless mode suppresses the graphical user interface (GUI), the standard F12 Developer Tools window is unavailable, meaning the browser's internal console output is discarded unless explicitly captured via a programmatic bridge. By hooking into the console events, you can debug JavaScript errors, track network warnings, and verify that your application logic is executing correctly in a non-visual environment.

What You'll Need

  • Node.js installed on your machine (required for Puppeteer and Playwright).
  • A headless browser driver (Puppeteer, Playwright, or Selenium WebDriver).
  • A code editor (such as VS Code) to write the implementation script.
  • A target URL or local HTML file to test the logging functionality.
  • Basic familiarity with asynchronous JavaScript (async/await) to handle the event-driven nature of browser logs.

Step-by-Step

  1. Initialize Your Project: Start by creating a new directory for your debugging script. Initialize a Node.js project by running npm init -y in your terminal. This ensures you have a package.json file to manage your dependencies.
  2. Install the Automation Library: Depending on your preference, install Puppeteer or Playwright. For Puppeteer, run npm install puppeteer. For Playwright, run npm install playwright. These libraries provide the necessary API to communicate with the Chrome DevTools Protocol.
  3. Launch the Browser in Headless Mode: Create a script (e.g., debug.js) and launch the browser. Ensure the headless option is set to true. While you can set it to false for visual debugging, the goal here is to capture logs specifically when the GUI is absent.
  4. Set Up the Console Event Listener: This is the critical step. You must attach a listener to the page object. In Puppeteer, use page.on('console', msg => { ... }). In Playwright, use page.on('console', msg => { ... }). Inside the callback function, you should access the message type (log, error, warning, info) and the actual text content of the log.
  5. Handle Complex Log Objects: Console logs are not always simple strings. Often, they are objects or arrays. To avoid seeing [object Object] in your terminal, you must iterate through the arguments of the console message and use JSON.stringify()` or a similar method to serialize the data into a readable format.
  6. Implement Error Catching for Page Crashes: Beyond standard console errors, you should listen for page crashes or uncaught exceptions. Use page.on('pageerror', err => { ... }) to capture JavaScript exceptions that occur within the page context but might not be explicitly logged via console.error().
  7. Navigate to the Target Page: Use page.goto('your-url-here'). As the page loads, the browser will execute the JavaScript on the site. Any console.log or console.error calls triggered during the loading process or by user interactions will now be piped through your listener to your terminal.
  8. Execute a Test Action: If the logs you are looking for only appear after a specific interaction (like clicking a button), use page.click('.selector'). The listener you established in step 4 remains active throughout the session, capturing all events in real-time.
  9. Close the Browser: Once you have captured the necessary logs, call await browser.close() to free up system resources and terminate the Chrome process.

Common Mistakes

One of the most frequent errors is failing to account for the asynchronous nature of the Chrome DevTools Protocol. Developers often place the page.on('console') listener after the page.goto() call. Because the browser begins executing JavaScript the moment the page starts loading, any logs generated during the initial page load will be missed if the listener is not attached beforehand. Always define your event listeners immediately after creating the page object and before initiating navigation.

Another common mistake is neglecting the difference between a console.error and a pageerror. A console.error is a deliberate call made by the developer using the console API. A pageerror is an uncaught exception (like a TypeError or ReferenceError) that crashes a script. If you only listen for 'console' events, you will miss the most critical crashes that cause your headless automation to fail. You must implement both listeners to get a complete picture of the browser's health.

Many users also forget to handle the args array in the console message object. The console event provides a message object that contains an array of arguments. If a developer wrote console.log('User data:', userObject), the string 'User data:' is the first argument and the object is the second. Simply printing msg.text() may only return the first string or a truncated version of the object, leading the debugger to believe the data is missing when it is actually just not serialized.

Tips

To make your logs more readable, implement a color-coding system in your terminal. Using a library like chalk, you can print console.log messages in green, console.warn in yellow, and console.error in red. This allows you to scan through thousands of lines of output quickly to find the exact moment a failure occurred.

For long-running tests, avoid printing everything to the terminal, as this can slow down execution and clutter your screen. Instead, pipe the output to a local log file using the Node.js fs (File System) module. By appending each console event to a debug.log file, you can use tools like grep or a text editor's search function to find specific error codes or keywords after the test suite has finished.

If you are debugging a complex Single Page Application (SPA), use the page.on('requestfailed') listener in conjunction with console logs. Often, a console error is merely a symptom of a failed network request (like a 404 or 500 error). By logging both the network failures and the console errors, you can correlate the two and identify if a missing API response is what triggered the JavaScript exception.

Troubleshooting

If you have implemented the listener but are still not seeing any logs, first verify that the site you are testing actually produces logs in a headed browser. Open the site in a standard Chrome window, press F12, and ensure the logs are visible. If they are, check if the site has logic that detects headless browsers (using navigator.webdriver) and disables certain features or logging when it detects automation. In such cases, you may need to use a plugin like puppeteer-extra-plugin-stealth to hide the headless nature of the browser.

If you see [object Object] instead of actual data, it means you are calling toString() on a JavaScript object. To fix this, iterate through the msg.args() collection. For each argument, check if it is an object; if so, use JSON.stringify(arg.value(), null, 2) to expand the object into a readable JSON string. This is essential for debugging API responses that are logged to the console.

In cases where the browser process hangs or crashes without any log output, check your system's memory. Headless Chrome can be resource-intensive, especially when multiple pages are open. If the OS kills the Chrome process (OOM Killer), no console logs will be emitted because the process died before the event could be sent to the Node.js bridge. Try launching Chrome with the --disable-dev-shm-usage flag to prevent crashes in Docker or Linux environments where /dev/shm is too small.

Frequently Asked Questions

Can I view console logs in real-time without a script?

No, because headless Chrome has no GUI, there is no built-in window to view logs. You must use a driver like Puppeteer or Playwright to capture and print the logs to your terminal.

Does this capture network errors like 404s?

Not by default. console.log only captures what the developer explicitly sends to the console. To capture 404 or 500 errors, you must listen for the requestfailed or response events in your automation library.

Will this slow down my headless browser performance?

The performance impact is negligible for most applications. However, if the page generates thousands of logs per second, the overhead of piping those messages to the Node.js process can cause a slight slowdown.

Can I filter logs to only show errors?

Yes. Inside your page.on('console') callback, you can check the message type using msg.type(). Use an if statement to only print the message if msg.type() === 'error'.

Does this work with Chrome in 'new' headless mode?

Yes, it works with both the legacy --headless mode and the newer --headless=new mode, as both utilize the same Chrome DevTools Protocol for event emission.