Skip to content

Instantly share code, notes, and snippets.

@DexterHaslem
Created June 7, 2022 04:30
Show Gist options
  • Save DexterHaslem/01c9e193c79ab5ceda129c3b910bd802 to your computer and use it in GitHub Desktop.
Save DexterHaslem/01c9e193c79ab5ceda129c3b910bd802 to your computer and use it in GitHub Desktop.
Intercept XHR requests so that we can do something useful with it.
// Taken from https://stackoverflow.com/a/27363569
// Allows for the object to be interrogated
((() => {
const origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
console.log('request started!');
this.addEventListener('load', function() {
console.log('request completed!');
console.log(this.readyState); //will always be 4 (ajax is completed successfully)
console.log(this.responseText); //whatever the response was
});
origOpen.apply(this, arguments);
};
}))();
// Taken from https://stackoverflow.com/a/5202999
// This is only good for logging.
function addXMLRequestCallback(callback){
let oldSend;
let i;
if( XMLHttpRequest.callbacks ) {
// we've already overridden send() so just add the callback
XMLHttpRequest.callbacks.push( callback );
} else {
// create a callback queue
XMLHttpRequest.callbacks = [callback];
// store the native send()
oldSend = XMLHttpRequest.prototype.send;
// override the native send()
XMLHttpRequest.prototype.send = function(){
// process the callback queue
// the xhr instance is passed into each callback but seems pretty useless
// you can't tell what its destination is or call abort() without an error
// so only really good for logging that a request has happened
// I could be wrong, I hope so...
// EDIT: I suppose you could override the onreadystatechange handler though
for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
XMLHttpRequest.callbacks[i]( this );
}
// call the native send()
oldSend.apply(this, arguments);
}
}
}
// e.g.
addXMLRequestCallback( xhr => {
console.log( xhr.responseText ); // (an empty string)
});
addXMLRequestCallback( xhr => {
console.dir( xhr ); // have a look if there is anything useful here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment