User Agents

Web browsers and everyday web tech, explained

Enable Local Overrides in Headless Chrome with Puppeteer

· 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

Enabling local overrides in headless Chrome with Puppeteer allows developers to simulate persistent changes to web resources—such as JavaScript, CSS, or HTML files—during automated testing or scraping. This feature mimics Chrome DevTools' Overrides functionality, letting you modify network responses and save them locally so they persist across page reloads and sessions. It's particularly useful for testing frontend changes without altering the original server content or for mocking API responses during browser automation.

What You'll Need

  • Node.js installed (version 14 or higher recommended)
  • Puppeteer installed via npm (npm install puppeteer)
  • A local directory to store override files and mappings
  • Basic knowledge of JavaScript and asynchronous programming
  • Chrome DevTools Protocol (CDP) understanding (helpful but not required)

Step-by-Step

  1. Initialize a Puppeteer project: Create a new directory and run npm init -y, then install Puppeteer with npm install puppeteer. This sets up the environment for browser automation.
  2. Enable DevTools Protocol access: Puppeteer uses the Chrome DevTools Protocol (CDP) under the hood. To enable overrides, you must connect to CDP domains. In your script, launch Chrome with const browser = await puppeteer.launch({ headless: true }); and obtain a CDP session using const client = await browser.createCDPSession();.
  3. Enable the necessary CDP domains: Overrides rely on the Page, Network, and DOMStorage domains. Run await client.send('Page.enable');, await client.send('Network.enable');, and await client.send('DOMStorage.enable'); to activate them.
  4. Set up a local override directory: Choose a local folder (e.g., ./overrides) where modified resources will be stored. Ensure Puppeteer has read/write access to this folder. This directory will mirror the website’s structure.
  5. Enable local overrides via CDP: Use await client.send('Fetch.enable', { patterns: [{ urlPattern: '*' }] }); to intercept all network requests. This allows Puppeteer to capture and potentially modify any resource.
  6. Handle intercepted requests: Set up a listener for the Fetch.requestPaused event. Inside the listener, extract the request URL and map it to a file path in your override directory. For example: const filePath = path.join('overrides', new URL(request.url).hostname, new URL(request.url).pathname);.
  7. Check for local override files: Use Node.js fs to check if a file exists at the mapped path. If it does, read its contents and fulfill the request using client.send('Fetch.fulfillRequest', { requestId, responseCode: 200, body: fs.readFileSync(filePath, 'base64'), responseHeaders: [{ name: 'Content-Type', value: 'text/javascript' }] });.
  8. Continue non-overridden requests: If no override file exists, use client.send('Fetch.continueRequest', { requestId }); to allow the original request to proceed. This ensures only modified resources are overridden.
  9. Save responses for future use: Optionally, listen to Network.responseReceived and Network.loadingFinished to capture and save original responses to the override directory. This creates a baseline for later editing.
  10. Test with a modified script: Create a test override file (e.g., ./overrides/example.com/script.js) with altered content. Run your Puppeteer script and verify the page loads the modified version.
  11. Handle dynamic content and caching: Disable cache during testing with await client.send('Network.setCacheDisabled', { cacheDisabled: true }); to ensure fresh responses. Re-enable as needed for production-like behavior.
  12. Close sessions properly: After testing, call await client.send('Fetch.disable'); and await browser.close(); to clean up resources and avoid memory leaks.

Common Mistakes

  • Forgetting to enable CDP domains: If Page or Network domains aren’t enabled, override commands will fail silently or throw errors.
  • Incorrect file path mapping: URLs with query strings or dynamic paths may not map cleanly to file paths. Always sanitize paths and handle edge cases like trailing slashes.
  • Not disabling cache: Cached responses can bypass overrides, making it seem like changes aren’t applied.
  • Overriding all requests indiscriminately: Using * in urlPattern can slow down execution. Consider filtering to specific domains or file types.
  • Ignoring response headers: When fulfilling requests, set appropriate Content-Type headers; otherwise, browsers may misinterpret the content.

Tips

  • Use a consistent directory structure that mirrors the domain and path hierarchy for easier management.
  • Log intercepted requests to debug which resources are being captured and which are being overridden.
  • Automate the creation of override directories using fs.mkdirSync(dirPath, { recursive: true }); when a new path is encountered.
  • Consider using environment variables to toggle override mode on or off during testing.
  • Use page.on('console', msg => console.log('PAGE LOG:', msg.text())) to catch runtime errors in overridden scripts.

Troubleshooting

If local overrides aren't working, first verify that the CDP session is active and domains are enabled. Check that the override directory exists and contains correctly named files matching the URL paths. Ensure file permissions allow reading. If requests aren’t intercepted, confirm that Fetch.enable was called with a valid pattern. Use console.log statements in the requestPaused handler to trace execution. If overridden content fails to load, inspect the base64 encoding—incorrect encoding will break responses. Test with a simple static file first. If Puppeteer crashes, ensure you’re not handling requestId reuse; each request must be fulfilled or continued exactly once. Finally, run in headless: false temporarily to visually confirm behavior.

Frequently Asked Questions

Can I use local overrides in headless mode?

Yes, local overrides work in headless mode using the Chrome DevTools Protocol via Puppeteer’s CDP session.

Do I need Chrome DevTools open to use overrides?

No, overrides are handled programmatically through CDP commands; no manual DevTools interaction is required.

Can I override API responses?

Yes, by intercepting XHR/fetch requests and fulfilling them with mock JSON data from local files.

Are cookies and localStorage affected?

No, local overrides only affect network resources; storage APIs are separate and must be mocked independently.

Does this work with HTTPS sites?

Yes, but ensure Puppeteer can handle SSL certificates; no additional setup is needed for basic overrides.

Can I edit files while Puppeteer is running?

Yes, changes to override files are read on each request, so live editing is supported during active sessions.