relm relm - 1 year ago 153
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 Source

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){ = 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, method, url, async, username, password);

You could also rewrite the XHR send() function:

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download