4

For the past days, we've been trying to develop a Devtools extension that could intercept only XHR requests. We can use the chrome.webRequest API on a normal extension, but that is not possible on a Devtools Extension Panel. We tried to used the devtools.network, but it catches all requests.

Is there a way to catch only the XHR requests?

Thanks in advance.

Bruno Santos
  • 154
  • 1
  • 8
  • This is the way I have done it https://stackoverflow.com/questions/58325758/create-a-har-file-with-xhr-request-only-in-chrome-dev-tools – Sandeepa Oct 13 '19 at 11:18

1 Answers1

5

You can use the chrome.devtools.network API to get the HAR, and then you can determine whether a request is XHR or not, filtering the output.

I'm not totally sure how DevTools determines this, but the X-Requested-With header is (typically) sent when AJAX requests are made. It is a non-standard, but is used widely. You can check for the XMLHttpRequest value in the HAR.

It's possible this doesn't catch all the requests, and there might be some other data DevTools uses, but here's a little snippet I created that will filter the HAR based on this header.

chrome.devtools.network.getHAR(function(result) {
    var entries = result.entries;
    var xhrEntries = entries.filter(function(entry) {
        var headers = entry.request.headers;

        var xhrHeader = headers.filter(function(header) {
            return header.name.toLowerCase() === 'x-requested-with' 
                && header.value === 'XMLHttpRequest';
        });

        return xhrHeader.length > 0;

    });

    console.log(xhrEntries);
});

Note. You can access the HAR data in the same way, per request, as it finishes, using the chrome.devtools.network.onRequestFinished event.

Gideon Pyzer
  • 22,610
  • 7
  • 62
  • 68
  • Thanks for the quick response! Unfortunately, the problem is that we've been testing in a lot of websites and the majority of them does not use the X-Requested-With header. Nonetheless, having in mind this problem, your solution works perfectly and if theres no other way, we will probably go with it. – Bruno Santos Feb 22 '17 at 10:40
  • 1
    @BrunoSantos I've asked on a group about how DevTools accomplishes this filter so I'll see if anyone comes back with anything useful. I think perhaps they might be doing some instrumentation on the XHR object to flag the request type rather than anything server related. It's one way they could have achieved it, but will see. – Gideon Pyzer Feb 22 '17 at 15:51
  • Thanks a lot! Keep me updated, and if in the meantime I find something useful, I'll share it here. – Bruno Santos Feb 23 '17 at 00:21