Yes, it's possible. Let me explain with an example. Here we have a simple AJAX call:
function loadDoc() {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = () => {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
The call is made by creating a new object from XMLHttpRequest and then the object is used for everything. You would have to tap into the object created there in order to intercept the call. That's usually not possible. What you can do, however, is proxy the point at which that object is created, so that you control what extra stuff the object does in certain situations:
// we have to overwrite the original XMLHttpRequest with our own version of it
XMLHttpRequest = class extends XMLHttpRequest {// by extending, we copy over all the original functionality
send() { // we overwrite the send function
// then we proxy the onreadystatechange property
this._onreadystatechange = this.onreadystatechange;
this.onreadystatechange = () => {
// Do your stuff here!
console.log('Ready State: ' + this.readyState);
if (typeof this._onreadystatechange === 'function') {
this._onreadystatechange();// call original event handler
}
};
super.send();// finally, we call the original send function
};
};
Done and tested on Hashnode :) Remember, though, this is a hackaround and it won't work in certain situations (like, when you set the onreadystatechange property after send() in your normal AJAX request code. I do not know of any better solution