Skip to content Skip to sidebar Skip to footer

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, howev

Solution 1:

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

Solution 2:

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;

Solution 3:

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

Post a Comment for "Overriding Xmlhttprequest's Send Method"