relm relm - 28 days ago 17
jQuery Question

Capture XHR with jQuery?

I'm using PhantomJS with jQuery and I'm wondering if it's possible to capture an XMLHttpRequest as it's passed to the browser, without initiating the POST/GET yourself.

Answer

There are simple jQuery functions that will let you modify AJAX requests before they are sent, but they only target AJAX requests initiated by jQuery. To catch all AJAX requests on a page, use the following basic JS-only way:

(function(open){
    XMLHttpRequest.prototype.open = function(method, url, async, username, password) {
        // modify the variables here as needed or use 'this` keyword to change the XHR object or add event listeners to it
        open.call(this, method, url, async, username, password);
    };
})(XMLHttpRequest.prototype.open);

You could also rewrite the XHR send() function:

(function(send){
    XMLHttpRequest.prototype.send = function(body) {
       // your code
       send.call(this, body);
    };
})(XMLHttpRequest.prototype.send);

Basically, this code needs to be the FIRST code that runs on your page. All subsequent XHR requests will go through the rewritten function(s), allowing you to change any parameters, etc.

Note: if you wish to target some versions of IE, you need to implement similar code for the ActiveXObject that IE uses for AJAX.