How to intercept all AJAX requests made by different JS libraries

As kindly pointed out by by Firefox AMO Editor Rob W,

The following code changes the behavior of XMLHttpRequest. By default, if the third ("async") parameter is not specified, it defaults to true. When it is specified and undefined, it is equivalent to "false", which turns a request in a synchronous HTTP request. This causes the UI to block while the request is being processed, and some features of the XMLHttpRequest API are disabled too.

...

To fix this, replace open.call(....) with open.apply(this, arguments);

And here is a reference link:

https://xhr.spec.whatwg.org/#the-open()-method


This won't catch XMLHttpRequests for some versions of IE (9 and below). Depending upon the library, they may look for IE's proprietary ActiveX control first.

And, of course, all bets are off if you are using a non-strict DOCTYPE under IE, but I'm sure you knew that.

Reference: CanIuse


Try this

let oldXHROpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {

console.log({method});

// Show loader

 this.addEventListener('load', function() {
  console.log('load: ' + this.responseText);
  // Hide loader
 });
           
  return oldXHROpen.apply(this, arguments);
}

This type of function hooking is perfectly safe and is done regularly on other methods for other reasons.

And, the only performance impact is really only one extra function call for each .open() plus whatever code you execute yourself which is probably immaterial when a networking call is involved.


In IE, this won't catch any code that tries to use the ActiveXObject control method of doing Ajax. Well written code looks first for the XMLHttpRequest object and uses that if available and that has been available since IE 7. But, there could be some code that uses the ActiveXObject method if it's available which would be true through much later versions of IE.


In modern browsers, there are other ways to issue Ajax calls such as the fetch() interface so if one is looking to hook all Ajax calls, you have to hook more than just XMLHttpRequest.