11

I'm trying to log (and later modify) the data XMLHttpRequest sends to a server by overriding XMLHttpRequest.send function.

My function logs the data correctly to the console, however the request doesn't finish, therefore the browser keeps waiting for the response indefinitely.

Any ideas what's wrong with the code?

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) { console.log("data: " + vData); realSend(vData); };
XMLHttpRequest.prototype.send = newSend;
Matteo Guarnerio
  • 720
  • 2
  • 9
  • 26
user1268760
  • 145
  • 1
  • 1
  • 6
  • Possible duplicate of http://stackoverflow.com/questions/4410218/trying-to-keep-track-of-number-of-outstanding-ajax-requests-in-firefox – Adriano Repetti Mar 14 '12 at 11:22

3 Answers3

24

You have forgot this:

this.realSend(vData);

However, you don't need to add a new method to the prototype:

var send = XMLHttpRequest.prototype.send;

XMLHttpRequest.prototype.send = function(data) {
    send.call(this, data);
}

Using closure, you can also avoid rogue variables:

!function(send){
    XMLHttpRequest.prototype.send = function (data) {
        send.call(this, data);
    }
}(XMLHttpRequest.prototype.send);
ZER0
  • 24,846
  • 5
  • 51
  • 54
21
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
// here "this" points to the XMLHttpRequest Object.
var newSend = function(vData) { console.log("data: " + vData); this.realSend(vData); };
XMLHttpRequest.prototype.send = newSend;
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Assuming the data to change is a JSON string you can write an interceptor like this one:

// Closure to contain variables and ! to avoid possible concatenation issues with other codes.
!function(){
  XMLHttpRequest.prototype._original_send = XMLHttpRequest.prototype.send;
  let interceptor_send = function(data){
    try {
      // Adding data to the JSON string, 
      // translating in JSON object to validate it's content and add an attribute.
      obj = JSON.parse(data);
      obj._custom_added_data = 'Your data';
      let new_data = JSON.stringify(obj);
      this._original_send(new_data);
    }
    catch(err) {
      // In case the payload was not a JSON string,
      // do not add anything and send the original payload.
      this._original_send(data);
    }

};
XMLHttpRequest.prototype.send = interceptor_send;
}();

Matteo Guarnerio
  • 720
  • 2
  • 9
  • 26