User Agents

Web browsers and everyday web tech, explained

Capture JS Errors in Headless Chrome with Puppeteer & CDP

· 5 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

Capturing JavaScript errors in headless Chrome allows developers to detect runtime crashes, uncaught exceptions, and console errors that occur during automated testing or web scraping. By leveraging the Chrome DevTools Protocol (CDP), you can intercept low-level browser events that standard page listeners might miss, ensuring that your headless environment mirrors the visibility of a headed browser's console.

What You'll Need

  • Node.js installed on your local machine or server.
  • A project initialized with npm init.
  • Puppeteer or Playwright installed via npm.
  • Basic familiarity with asynchronous JavaScript (async/await).

Step-by-Step

  1. Initialize the Browser Instance: Start by launching your browser in headless mode. While Puppeteer and Playwright both support headless operation, the method for accessing the CDP session differs slightly. Ensure you have the necessary permissions to launch the process in your environment.
  2. Establish a CDP Session: To capture errors that happen before the page script even loads, you must connect to the Chrome DevTools Protocol. In Puppeteer, use page._client.send or create a new session via browser.target().createCDPSession(). In Playwright, use page.context().newCDPSession(page).
  3. Enable Runtime Monitoring: You must explicitly tell the browser to start reporting runtime exceptions. Send the Runtime.enable command through your CDP session. This activates the event stream that broadcasts JavaScript execution errors to your Node.js process.
  4. Set Up the Event Listener: Create a listener for the Runtime.consoleAPICalled or Runtime.exceptionThrown events. The exceptionThrown event is particularly powerful because it captures uncaught exceptions, including the stack trace and the specific line of code where the failure occurred.
  5. Implement Page-Level Listeners: While CDP handles the protocol level, you should also implement page.on('pageerror') (Puppeteer) or page.on('pageerror') (Playwright). This captures errors that are thrown within the page's execution context and provides a higher-level JavaScript Error object.
  6. Capture Console Logs: Many JavaScript errors are logged via console.error() rather than being thrown as exceptions. Listen for the console event on the page object to capture these logs, as they often contain critical debugging information provided by third-party libraries.
  7. Execute the Page Navigation: Navigate to your target URL. Because you established the CDP session and listeners before calling page.goto(), you will capture errors that occur during the initial parsing and execution of the page's scripts.
  8. Aggregate and Log Errors: Create a central array or logging function to collect all intercepted errors. This allows you to fail your test suite or trigger an alert if a critical JS error is detected during the session.

Common Mistakes

  • Listening After Navigation: The most frequent error is calling page.goto() before setting up the CDP session or page listeners. This results in missing all errors that occur during the initial page load.
  • Ignoring Console Errors: Relying solely on pageerror. Many modern frameworks catch their own exceptions and log them to the console instead of letting them bubble up to the window object.
  • Overlooking Cross-Origin Scripts: Errors occurring in scripts hosted on different domains (CDNs) may be masked as "Script error." To fix this, ensure the server sends the Access-Control-Allow-Origin header and the script tag includes the crossorigin attribute.
  • Memory Leaks: Creating new CDP sessions for every single request without closing them, which can lead to significant memory overhead in long-running scraping tasks.

Tips

  • Filter Noise: In production environments, some third-party scripts (like ads or analytics) throw harmless errors. Implement a filter list to ignore known non-critical errors to avoid false positives in your monitoring.
  • Capture Screenshots: When a JS error is detected, trigger page.screenshot() immediately. This provides visual context of the page state at the exact moment the crash occurred.
  • Use Detailed CDP Events: Use Runtime.exceptionThrown with the exceptionPause parameter set to false to log errors without pausing the execution of the browser.
  • Combine with Network Interception: Often, JS errors are caused by failed API calls. Use page.on('requestfailed') alongside your error listeners to correlate network timeouts with JavaScript crashes.

Troubleshooting

If you are not seeing errors that you know exist in the headed browser, first verify that you are not in a "silent" mode where the application's own global error handler (like Sentry or a custom window.onerror) is suppressing the event. You may need to override these handlers using page.evaluate() to ensure the errors reach the browser's top-level context.

If the CDP session fails to connect, ensure you are using a compatible version of Chromium. Playwright and Puppeteer are bundled with specific browser versions; using a system-installed Chrome that is significantly newer or older than the library's expectation can cause protocol mismatches.

For "Script error." messages with no stack trace, check the crossorigin attribute on your <script> tags. Without this, Chrome hides the details of the error for security reasons when the script is hosted on a different domain.

Frequently Asked Questions

Does this work for Single Page Applications (SPAs)?

Yes, this method is highly effective for SPAs (React, Vue, Angular) because it monitors the runtime environment continuously, capturing errors that occur during client-side routing or state updates.

What is the difference between pageerror and CDP exceptions?

pageerror is a high-level wrapper provided by the library for uncaught exceptions. CDP's Runtime.exceptionThrown is a low-level protocol event that can provide more granular detail and can be captured even before the page context is fully initialized.

Can I capture errors from iframes?

Yes, but you must ensure your listeners are attached to the correct frame. While CDP captures most global runtime events, page.on('pageerror') may require you to iterate through page.frames() to catch errors originating inside nested iframes.

Will this slow down the page load time?

The performance impact is negligible. Enabling CDP runtime monitoring adds a very small amount of overhead that is typically imperceptible during automated testing or scraping.

Do I need to use a specific version of Node.js?

Any LTS version of Node.js that supports async/await is sufficient. Ensure your npm packages are updated to the latest versions to maintain compatibility with the current Chrome DevTools Protocol.