Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override post requests

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?

like image 562
Phenomenon Avatar asked Oct 16 '21 03:10

Phenomenon


3 Answers

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.

like image 120
Ruslan Zhomir Avatar answered Oct 10 '22 01:10

Ruslan Zhomir


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.

like image 25
Andrew Stegmaier Avatar answered Oct 10 '22 02:10

Andrew Stegmaier


If your function is not being called, possible fetch is used to make ajax requests.

So you can wrap both functions, like this

const send = XMLHttpRequest.prototype.send;
const _fetch = window.fetch;

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

window.fetch = function(url, options){
   let newBody;
   if(options.body) {
      newBody = JSON.parse(options.body);
      newBody.points = 417;
      options.body = JSON.stringify(newBody);
   }
   _fetch.call(this, url, options);
}
like image 1
Shimon Brandsdorfer Avatar answered Oct 10 '22 00:10

Shimon Brandsdorfer