JavaScript: Detect AJAX requests

Here’s some code (tested by pasting into Chrome 31.0.1650.63’s console) for catching and logging or otherwise processing ajax requests and their responses:

(function() {
    var proxied = window.XMLHttpRequest.prototype.send;
    window.XMLHttpRequest.prototype.send = function() {
        console.log( arguments );
        //Here is where you can add any code to process the request. 
        //If you want to pass the Ajax request object, pass the 'pointer' below
        var pointer = this
        var intervalId = window.setInterval(function(){
                if(pointer.readyState != 4){
                        return;
                }
                console.log( pointer.responseText );
                //Here is where you can add any code to process the response.
                //If you want to pass the Ajax request object, pass the 'pointer' below
                clearInterval(intervalId);

        }, 1);//I found a delay of 1 to be sufficient, modify it as you need.
        return proxied.apply(this, [].slice.call(arguments));
    };


})();

This code solves the above issue with the accepted answer:

Note that it may not work if you use frameworks (like jQuery), because
they may override onreadystatechange after calling send (I think
jQuery does). Or they can override send method (but this is unlikely).
So it is a partial solution.

Because it does not rely on the ‘onreadystatechange’ callback being un-changed, but monitors the ‘readyState’ itself.

I adapted the answer from here: https://stackoverflow.com/a/7778218/1153227

Leave a Comment