Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  38] [ 2]  / answers: 1 / hits: 59616  / 7 Years ago, mon, july 31, 2017, 12:00:00

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?


More From » ajax

 Answers
24

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

[#56905] Saturday, July 29, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hallie

Total Points: 503
Total Questions: 114
Total Answers: 103

Location: Iraq
Member since Fri, Jun 5, 2020
4 Years ago
;