Skip to content
Advertisement

Intercept fetch() API requests and responses in JavaScript

I want to intercept fetch API requests and responses in JavaScript.

For example, before sending the request I want to intercept the request URL. I’d like to intercept the response once it arrives as well.

The below code is for intercepting responses of all XMLHTTPRequests.

(function(open) {
  XMLHttpRequest.prototype.open = function(XMLHttpRequest) {
    var self = this;
    this.addEventListener("readystatechange", function() {
      if (this.responseText.length > 0 && 
          this.readyState == 4 && 
          this.responseURL.indexOf('www.google.com') >= 0) {

        Object.defineProperty(self, 'response', {
          get: function() { return bValue; },
          set: function(newValue) { bValue = newValue; },
          enumerable: true,
          configurable: true
        });
        self.response = 'updated value' // Intercepted Value 
      }
    }, false);
    open.apply(this, arguments);
  };
})(XMLHttpRequest.prototype.open);

I want to implement the same feature for fetch() API. How can I do this?

Advertisement

Answer

For intercepting the fetch request and parameter we can go for below mentioned way. its resolved my issue.

 const constantMock = window.fetch;
 window.fetch = function() {
     // Get the parameter in arguments
     // Intercept the parameter here 
    return constantMock.apply(this, arguments)
 }
Advertisement