Overriding XMLHttpRequest's send method

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;

Answers:

Answer
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;
Answer

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);
Answer

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;
}();

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.