Search code examples
javascriptxmlhttprequest

Is it possible to watch over XHR/Fetch requests happening in the browser?


I want to react to some events that are triggered by a 3rd party on my site. Those events are Fetch/XHR requests, I'd like to be notified when a "watched" request happens (I assume I would watch them based on the "Request URL"), and I would like to read its request/response headers and payload.

I've never seen that being done before, is it even possible?

The browser is aware of all requests happening, but I'm uncertain whether we can read this, can we?

Eventually, I hope to achieve a watcher that would trigger my own code when some endpoints have been called, while re-using the data sent by those requests. I'm hoping to both detect WHEN a particular endpoint is called, and WHAT the response is, so that I can use it for my own needs (without needing to perform yet another identical request)

I'm not sure if reading the data will be possible, I found out that reacting to fetch requests is possible with the help of Resource Timing (see https://www.w3.org/TR/resource-timing/)


Solution

  • It's possible using the WebRequest built-in library. The following example is specific to the Chrome Extension runtime, but something similar is doable for browsers, too.

    For Chrome Extensions, it needs to run as a Service Worker (e.g: background.js)*

    chrome.webRequest.onBeforeSendHeaders.addListener(
      (requestHeadersDetails) => {
        console.log('requestHeadersDetails', requestHeadersDetails);
      },
      {
        urls: ['https://*'],
      },
      [
        'requestHeaders',
        'extraHeaders',
      ],
    );
    

    See https://developer.chrome.com/docs/extensions/reference/webRequest/#event-onBeforeRequest and https://developer.chrome.com/docs/extensions/reference/webRequest/#event-onBeforeSendHeaders (both are very similar)

    I didn't find a way to re-use the data that were fetched, though. But at least I'm notified when a request is sent.