Skip to content
Advertisement

JavaScript: Detect AJAX requests

Is there any way to detect global AJAX calls (particularly responses) on a web page with generic JavaScript (not with frameworks)?

I’ve already reviewed the question “JavaScript detect an AJAX event“, here on StackOverflow, and tried patching in the accepted answer’s code into my application but it didn’t work. I’ve never done anything with AJAX before either so, I don’t know enough to modify it to work.

I don’t need anything fancy, I just need to detect all (specific, actually, but I’d have to detect all first and go from there) AJAX responses and patch them into an IF statement for use. So, eventually, I’d like something like:

if (ajax.response == "certainResponseType"){
    //Code
}

, for example.

Update: It seems I should clarify that I’m not trying to send a request – I’m developing a content script and I need to be able to detect the web page’s AJAX requests (not make my own), so I can execute a function when a response is detected.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement