User Agents

Web browsers and everyday web tech, explained

Capture AJAX Traffic with Headless Chrome Programmatically

· 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 AJAX traffic programmatically with headless Chrome allows you to intercept, analyze, and record the background HTTP requests a web application makes to its API. This is essential for automated testing, data scraping from dynamic sites, and debugging asynchronous network calls without manually opening the browser's Developer Tools. By leveraging the Chrome DevTools Protocol (CDP), you can listen for network events and extract request headers, payloads, and responses in real-time.

What You'll Need

  • Node.js installed on your machine.
  • Puppeteer or Playwright (the most common libraries for controlling headless Chrome).
  • Basic knowledge of JavaScript/TypeScript.
  • A target URL that performs asynchronous AJAX/Fetch requests.

Step-by-Step

  1. Initialize Your Project: Create a new directory for your script and initialize it with npm. Install Puppeteer, as it provides a direct interface to the Chrome DevTools Protocol. Run npm install puppeteer in your terminal.
  2. Launch the Browser: Import Puppeteer and launch a headless instance. While headless mode is the default, you can set headless: "new" (or true in older versions) in the launch options to ensure the browser runs in the background.
  3. Create a New Page: Use browser.newPage() to open a tab. This page object will be the primary interface for navigating to the website and attaching network listeners.
  4. Enable Network Request Interception: Use page.setRequestInterception(true). This tells Chrome to pause every single outgoing request, allowing your script to decide whether to continue, modify, or abort the request.
  5. Set Up the Request Listener: Implement the page.on('request', event => { ... }) listener. Inside this callback, you can filter for specific request types. For AJAX traffic, check if event.resourceType() is 'xhr' or 'fetch'.
  6. Capture Request Data: Within the listener, extract the necessary details. You can access the URL via event.url(), the HTTP method via event.method(), and the POST data (if applicable) via event.postData().
  7. Handle the Response: To capture the actual data returned by the server, use the page.on('response', response => { ... }) event. You can filter this by the same URL or resource type and then call await response.json() or await response.text() to retrieve the body of the AJAX response.
  8. Execute Navigation: Call await page.goto('your-url-here'). Once the page loads and the AJAX calls trigger, your listeners will automatically fire and log the traffic.
  9. Clean Up: Once the data is captured, close the page and the browser using await page.close() and await browser.close() to free up system resources.

Common Mistakes

  • Forgetting to call request.continue(): When setRequestInterception(true) is enabled, every request is paused. If you do not call request.continue() inside the 'request' event handler, the page will hang indefinitely and never load.
  • Ignoring Resource Types: Attempting to capture all traffic without filtering for xhr or fetch will flood your logs with CSS, images, and font files, making it difficult to find the actual API calls.
  • Race Conditions: Setting up the listeners after calling page.goto(). The listeners must be defined before the navigation starts, otherwise, the initial AJAX calls triggered during page load will be missed.
  • Memory Leaks: Failing to close the browser instance in a try...finally block, which can lead to orphaned Chrome processes consuming RAM.

Tips

  • Use a Proxy: For more advanced analysis or modification of traffic, consider routing headless Chrome through a debugging proxy like mitmproxy.
  • Filter by URL Patterns: Instead of capturing all AJAX, use a Regular Expression or .includes() on the URL to target only the specific API endpoints you care about.
  • Wait for Network Idle: Use await page.goto(url, { waitUntil: 'networkidle0' }). This ensures that Puppeteer waits until there are no more than 0 network connections for at least 500ms, ensuring all AJAX calls have completed.
  • Save to JSON: Instead of logging to the console, push the captured request and response pairs into an array and write them to a .json file using fs.writeFileSync() for later analysis.

Troubleshooting

If you are not seeing any traffic captured, first verify that the site is actually using AJAX/Fetch and not WebSockets. WebSockets require a different listener (page.on('websocket')). If the requests are happening but the response body is empty, ensure you are awaiting the response.json() call, as it is asynchronous.

If the page fails to load or requests time out, check if the site has bot detection. Headless Chrome has a distinct fingerprint. You may need to set a realistic User-Agent string using page.setUserAgent() to mimic a standard desktop browser.

In cases where setRequestInterception causes stability issues, try using the CDPSession. By calling const client = await page.target().createCDPSession() and enabling Network.enable, you can access lower-level events that are sometimes more reliable than the high-level Puppeteer API.

Frequently Asked Questions

Can I modify the AJAX request before it is sent?

Yes. By using setRequestInterception(true), you can use request.continue({ postData: 'new data' }) to change the payload or headers before the request reaches the server.

Does this work for Single Page Applications (SPAs)?

Yes, this method is ideal for SPAs (like those built with React, Vue, or Angular) because it monitors the network layer regardless of how the DOM is updated.

Is there a difference between capturing 'xhr' and 'fetch'?

Technically, yes. xhr refers to the older XMLHttpRequest API, while fetch refers to the modern Fetch API. Most modern sites use fetch, but you should listen for both to be thorough.

Can I capture traffic from iframes?

Yes, network listeners attached to the page object generally capture all traffic originating from that page, including requests made by embedded iframes.

Will this work in a Docker container?

Yes, but you must ensure the Docker image has the necessary Chrome dependencies installed and that you launch the browser with the --no-sandbox flag.