Skip to content

Instantly share code, notes, and snippets.

@bspavel
Created February 26, 2019 12:04
Show Gist options
  • Select an option

  • Save bspavel/966268a0727aaeefeb0ab6f59535f5c4 to your computer and use it in GitHub Desktop.

Select an option

Save bspavel/966268a0727aaeefeb0ab6f59535f5c4 to your computer and use it in GitHub Desktop.
Add a “hook” to all AJAX requests on a page
//https://stackoverflow.com/questions/5202296/add-a-hook-to-all-ajax-requests-on-a-page
function addXMLRequestCallback(callback){
var oldSend, 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( function( xhr ) {
console.log( xhr.responseText ); // (an empty string)
});
addXMLRequestCallback( function( 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