Home > Blockchain >  Override post requests
Override post requests

Time:10-21

I have this code that I put in my console:

XMLHttpRequest.prototype.send = function(body) {
    // modifies inputted request
    newBody = JSON.parse(body);
    newBody.points = 417;

  // sends modified request
    this.realSend(JSON.stringify(newBody));
}

It is supposed to make the points 417 every time it sends a request, but when I look at the request body, it still says the original amount of points. Any help?

CodePudding user response:

Try to add an alert() or console.log() into your modified XMLHttpRequest.prototype.send to check if it actually works. There is a way to prevent this kind of modifications silently.

CodePudding user response:

As others have noted, the error you are experiencing is hard to diagnose exactly without seeing how you created this.realSend.

However, this code will work:

const send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function (body) {
    const newBody = JSON.parse(body);
    newBody.points = 417;
    send.call(this, JSON.stringify(newBody));
};

Note that instead of storing the original send method on XMLHttpRequest.prototype, I've kept in a separate variable and simply invoked it with the correct this value through send.call(). This seems like a cleaner implementation with less chance for conflicts with other code.

See this codesandbox for a working example.

  • Related