Intercepting AJAX responses in JavaScript

Most webpages these days are a lot more interesting than in the early days of the internet. Instead of just being a blob of text, websites will now phone home to get new content or take input from a user. You can open your developer console and switch to the network tab and see all of this traffic for yourself.

Reading it is all well and good but what if you want to be able to process it with your own code. There is tremendous power in being able to do so. Instead of your browser just being a passive observer, you can decide to do whatever you want to with what the server returns. Thanks to the prototyping abilities of JavaScript this is straight forward to do.

const intercept = (urlmatch, callback) => {
  let send = XMLHttpRequest.prototype.send;
  XMLHttpRequest.prototype.send = function() {
    this.addEventListener('readystatechange', function() {
      if (this.responseURL.includes(urlmatch) && this.readyState === 4) {
        callback(this);
      }
    }, false);
    send.apply(this, arguments);
  };
};

See an example of intercepting a call to https://httpbin.org/ip at JSFiddle.