1

I'm creating a simple JavaScript code to intercept any AJAX request with the idea of add an extra param that I need to read in the server side (Java). Until now I have this code that I have tested with different kind of request, with and without jquery as well, works fine:

(function(open) { XMLHttpRequest.prototype.send = function() { console.log('Start a new AJAX request'); var myExtraParam = 'ABC123'; // value that I need to send, but it's dynamically, it will come from a function open.apply(this); }; })(XMLHttpRequest.prototype.send); 

What I have been looking is the way to attach an extra parameter, on this scenario, the variable "myExtraParam" when I call the apply method.

I'm using plain JavaScript

EDIT: As param, I'm asuming a value that I can read in the server, like when you do: myurl?myExtraParam=ABC123

11
  • So, you're asking how to add a parameter? What do you mean? A query parameter? Adding it to the payload body? A header? Commented Apr 4, 2018 at 14:26
  • I would set a header... Commented Apr 4, 2018 at 14:26
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. apply() is for sending an array as parameter. Commented Apr 4, 2018 at 14:26
  • You can't add it as a GET parameter when the request is already open, AFAIK. GET parameters are part of the URL and that cannot be changed after open() is called. So, you'll probably want to override open() instead. Commented Apr 4, 2018 at 14:30
  • Also note, in your example open.apply(this); will discard the arguments originally passed to send(). In such cases you should call open.apply(this, arguments); Commented Apr 4, 2018 at 14:36

1 Answer 1

1

Setting a parameter seems like a lot of work dealing with querystring or appending it to the request body. Safer thing seems to be using a header.

(function() { var orgSend = window.XMLHttpRequest.prototype.send; window.XMLHttpRequest.prototype.send = function() { this.setRequestHeader("foo", "bar") return orgSend.apply(this, [].slice.call(arguments)); }; })(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Certainly the best option, I have tested this with my servlet and works perfect, thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.