3

Is it possible to create a Javascript and include it in a web page that the function of this JS is to "catch" all GET request or any other Ajax calls made from any other Javascript on the page? Either to log it or just plain show it in a Alert box.

The "other Javacript" that will be executing GET or Ajax calls is arbitrary. I mean I have no control over that in terms of what it is.

And once caught I need to check which Javascript executing which GET or Ajax calls.

Is this possible?

quarks
  • 33,478
  • 73
  • 290
  • 513
  • Do you need this for debugging? All major browsers have this built in. – Yoshi Mar 29 '12 at 07:28
  • For now since it seems that its not easy with plain Javascript maybe I can use browser plugin, however Firebug does not show which Javascript initiated the GET method for example... – quarks Mar 29 '12 at 07:32
  • ...but my requirement is not really for debugging, but for actual application function. – quarks Mar 29 '12 at 08:44
  • ...but my requirement is not really for debugging, but for actual application function. – quarks Mar 29 '12 at 08:44
  • Then test @Jasd's solution. It's probably the right direction. Though you'll have to make sure your code runs before the first ajax request. – Yoshi Mar 29 '12 at 08:47
  • @Yoshi yes I have tested it and it worked for the Ajax part. – quarks Mar 29 '12 at 08:59

2 Answers2

12

Try this snippet. It extends the send function so that you can execute something before or after the real sending.

XMLHttpRequest.prototype.reallySend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(body) {
    // Do something...
    this.reallySend(body);
};
var req = new XMLHttpRequest();
req.open("GET", "any.html", true);
req.send(null);
Johannes Egger
  • 3,874
  • 27
  • 36
  • This worked and I was able to catch Ajax call, however I did not caught the request for the HTML I was expecting probably because its not Ajax call, do you know how to intercept GET events caused by Javascript? – quarks Mar 29 '12 at 08:53
  • @xybrek You can use this approach as a template. What you have to do is adept this to every method javascript has to make requests (e.g. the Image Object, ` – Yoshi Mar 29 '12 at 09:04
  • @xybrek Unfortunately I don't know such an event. Maybe it's best to follow Yoshi's advice to implement the solution for each element which can cause the browser to make a request. – Johannes Egger Mar 29 '12 at 09:46
  • @Yoshi can you site some example for your approach? – quarks Mar 29 '12 at 11:04
  • @xybrek sort of similar question: http://stackoverflow.com/a/9676178/697154 hope it helps – Yoshi Mar 29 '12 at 11:08
1
const nativeOpen = XMLHttpRequest.prototype.open;

const proxiedOpen = function () {
  if (arguments[1].includes('youUrl.com')) {
    // do some ...
  }
  nativeOpen.apply(this, arguments);
};

Refer to the answer:

Intercept AND CHANGE the results of an ajax call

weiya ou
  • 2,730
  • 1
  • 16
  • 24