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 XMLHTTPRequest
s.
JavaScript
x
21
21
1
(function(open) {
2
XMLHttpRequest.prototype.open = function(XMLHttpRequest) {
3
var self = this;
4
this.addEventListener("readystatechange", function() {
5
if (this.responseText.length > 0 &&
6
this.readyState == 4 &&
7
this.responseURL.indexOf('www.google.com') >= 0) {
8
9
Object.defineProperty(self, 'response', {
10
get: function() { return bValue; },
11
set: function(newValue) { bValue = newValue; },
12
enumerable: true,
13
configurable: true
14
});
15
self.response = 'updated value' // Intercepted Value
16
}
17
}, false);
18
open.apply(this, arguments);
19
};
20
})(XMLHttpRequest.prototype.open);
21
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.
JavaScript
1
7
1
const constantMock = window.fetch;
2
window.fetch = function() {
3
// Get the parameter in arguments
4
// Intercept the parameter here
5
return constantMock.apply(this, arguments)
6
}
7