How to intercept all network requests in a web page

46 Views Asked by At

I have a situation in which I need to monitor all network requests made by a web page. When I mean all network requests, I really mean absolutely all of them, that is:

  • all requests made from my web page (script or image downloads, XMLHttpRequest requests and so on...)
  • all requests made from scripts that have been downloaded from my web page, including scripts from other domains

In this latter case, if I am talking about the following scenario:

<!-- Let's say my web page is hosted at https://example.com/ -->
<html>
...
<script src="https://otherdomain.com/somescript.js"></script>
...
</html>

If somescript.js downloads stuff from the web, from its own domain or any other domain, I need to monitor that, too.

Is that at all possible?

So far, I tried with a service worker, and it does work, at least to some extent. Surprinsgly, some requests are not actually seen by my service worker. Its registration scope is /.

1

There are 1 best solutions below

2
Alexander Nenashev On

You could monkey patch fetch and XMLHttpRequest.prototype before your target scripts.

An example for fetch:

const _fetch = window.fetch;

const prop = Object.getOwnPropertyDescriptor(window, 'fetch');

let events = [];

prop.value = function () {

    console.log('fetch:', ...arguments);
    const out = _fetch.apply(window, arguments);

    out.then(function(response) {

        const _json = response.json;

        response.json = function () {
            const out = _json.call(response);
            out.then(data => {
                console.log(data);
                return data;
            });
            return out;
        }

        return response;
    });

    return out;

}

Object.defineProperty(window, 'fetch', prop);


fetch('https://jsonplaceholder.typicode.com/todos/1').then(r => r.json());