Intercept Fetch() API responses and request in Javascript

Hariharan Subramanian picture Hariharan Subramanian · Jul 31, 2017 · Viewed 16.8k times · Source

I want to intercept the fetch API request and response in Javascript.

For ex: Before sending the request want to intercept the request URL and once get the response wants to intercept the response.

The below code is for intercepting response of All XMLHTTPRequest.

(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 wan to implement the same feature for Fetch() API.

Thanks in Advance..

Answer

Hariharan Subramanian picture Hariharan Subramanian · Aug 25, 2017

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