0

I'm trying to intercept all the AJAX request made in plain vanilla JavaScript but what I've found on Stack Overflow doesn't seems to work.

The easiest (and I would say 'functional') code is the following :

 (function(open) {
  XMLHttpRequest.prototype.open = function() {
    alert('Intercept');
    open.apply(this, arguments);
  };
})(XMLHttpRequest.prototype.open);

I copy/pasted it on my current website that I know makes an AJAX request at some point, did the AJAX request, and no "alert" was displayed.

I'm using Chrome v49.0.2623.87

Is there a new reason that disabled it ?

halfer
  • 19,824
  • 17
  • 99
  • 186
Cyril N.
  • 38,875
  • 36
  • 142
  • 243
  • Works perfectly fine -> https://jsfiddle.net/dnyfbsy3/, you did of course add that rewrite of the `open` function before any ajax requests. – adeneo Apr 01 '16 at 16:03
  • Can you give the reference from where you get this code. – paraS elixiR Apr 01 '16 at 16:04
  • I added it on the fly from the console, but before making the call. Maybe it's the issue ? – Cyril N. Apr 01 '16 at 16:05
  • @paraSelixiR Yes absolutely, it's a simplfied version of http://stackoverflow.com/questions/629671/how-can-i-intercept-xmlhttprequests-from-a-greasemonkey-script?lq=1 – Cyril N. Apr 01 '16 at 16:05
  • Ok well apparently it must be added **before** any request is made, even a new one. I don't know why though, if anyone has an explanation ? – Cyril N. Apr 01 '16 at 16:08
  • It is because here 'open' is defined as a function expression ( var x = function(){..} ) and not as a function definition( function x(){} ). In case of function expression you can not call a function before it is defined. ref.https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ – paraS elixiR Apr 01 '16 at 16:16
  • 1
    This code runs over the XHR prototype, so if the XHR was instantiated before, it will reference the old 'open' method. Any new XHR *created* (as opposed to called) after it should reference the new open method – Omri Apr 01 '16 at 17:13
  • @Omri Thank you for your comment. But what I don't understand is that you make a `new XHR` everytime you make a new ajax request, so normally the new instance of XHR is created at each request, so why it doesn't work to update the xhr prototype later ; each subsequent requests should have the update code no ? – Cyril N. Apr 02 '16 at 08:07

0 Answers0