I’m looking to intercept fetch API requests and responses using JavaScript.
Specifically, I want to be able to capture the request URL before it is sent and also intercept the response once it has been received.
The code below demonstrates how to intercept responses for all instances of 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);
Now, I am interested in implementing a similar feature for the fetch()
API. How can I achieve this?