Alice
Alice

Reputation: 323

How to Intercept XMLHttpRequest and change request URL

My front send requests to the back server. How can I intercept this request, and redirect to another back? How can I change back's URL?

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

Thanks!

Upvotes: 2

Views: 7858

Answers (1)

Estus Flask
Estus Flask

Reputation: 222369

This can be easily achieved by patching XMLHttpRequest open:

const intercept = (urlmatch, newurl) => {
  const open = XMLHttpRequest.prototype.open;
  XMLHttpRequest.prototype.open = function (method, url, ...rest) {
    url = url.replace(urlmatch, newurl);
    return open.call(this, method, url, ...rest);
  };
}

intercept('http:/example.com/', 'http:/my-example.com/');

Modifying globals for local needs is a bad practice that may lead to unforseen consequences.

Unless the goal is to tamper somebody else's application (for instance, with user script), a cleaner way is to modify the application to make it possible to change base url, e.g. from

makeRequest('http:/example.com/api/...')

to

makeRequest(BASE_API_URL + '...')

Where BASE_API_URL is application constant that can be changed on application initialization, with environment variables, globals, dependency injection, etc.

If an application uses some kind of a wrapper instead of XMLHttpRequest directly, base URL functionality may be implemented in a wrapper.

Upvotes: 8

Related Questions