quarks
quarks

Reputation: 35276

Intercept or catch Ajax Calls with Javascript

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?

Upvotes: 3

Views: 8796

Answers (2)

weiya ou
weiya ou

Reputation: 4320

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

Upvotes: 1

Johannes Egger
Johannes Egger

Reputation: 4041

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);

Upvotes: 12

Related Questions