24hours
24hours

Reputation: 191

How to add a callback to every AJAX request / response event.

Im trying to inject javascript into webpage and capture all the ajax request made.

function addXMLRequestCallback(send_callback) {
    var oldSend, i;
    if(XMLHttpRequest.send_callbacks) {
        XMLHttpRequest.send_callbacks.push(send_callback);
    } else {
        XMLHttpRequest.send_callbacks = [send_callback];
        oldSend = XMLHttpRequest.prototype.send;
        XMLHttpRequest.prototype.send = function () {
            for (i = 0; i < XMLHttpRequest.send_callbacks.length; i++) {
                XMLHttpRequest.send_callbacks[i](this, arguments);
            }
            oldSend.apply(this, arguments);
        }
    }
}

*copied somewhere from SO

this function allow me to capture all the send() event, but i want to capture XMLHttpRequest.responseText as well, which require XMLHttpRequest.onload. The method above does not work on XMLHttpRequest.onload since it is not really a function, and directly assign function to onload event will eventually get override by other script that using the instance.

is there a method that i can assign call back to onload event without it getting override ?

Upvotes: 1

Views: 238

Answers (2)

Gugic
Gugic

Reputation: 109

Or you can try to totally change XMLHttpRequest with your own object. (But it's dirty hack and you should not do things like that. Also it can be unpredictable).

Solution of Niet the Dark Absol is obviously better

var oldRequest = XMLHttpRequest;
XMLHttpRequest = function(){
    var returnObject = new oldRequest();
    returnObject.addEventListener('load',function(){console.log('load callback fired')})
    return returnObject;
}

var req = new XMLHttpRequest(); //req with callback;

Upvotes: -1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

You can use the "more standard" way:

Right before oldSend.apply(this,arguments), add the following:

this.addEventListener("load",function() {
    // do something with this.responseText
},false);

Upvotes: 2

Related Questions