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;


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;

You have forgot this:


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:

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

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.
  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);
    catch(err) {
      // In case the payload was not a JSON string,
      // do not add anything and send the original payload.

XMLHttpRequest.prototype.send = interceptor_send;


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.