Skip to content

Instantly share code, notes, and snippets.

@vhsu
Last active August 31, 2021 08:27
Show Gist options
  • Save vhsu/bf28bf577cce6016b2dc to your computer and use it in GitHub Desktop.
Save vhsu/bf28bf577cce6016b2dc to your computer and use it in GitHub Desktop.
Check for Ajax
// Overwrites Ajax requests on a page, used to track ajax stuff with tag manager, or to test stuff with visual website
// optimizer or optimizely
function addXMLRequestCallback(callback){
let 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(){
// 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);
}
}
}
addXMLRequestCallback( function( xhr ) {
setTimeout(function(){dothedance()}, 400);
});
// example function
function dothedance(){
alert('Some Ajax is going on');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment