I'm trying to run some simple JS functions after every request to the server with the Fetch API. I've searched for an answer to this question, but haven't found any, perhaps due to the fact that the Fetch API is relative recent.
I've been doing this with XMLHttpRequest
like so:
(function () {
var origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
this.addEventListener('load', function () {
someFunctionToDoSomething();
});
origOpen.apply(this, arguments);
};
})();
Would be great to know if there's a way to accomplish this very same global thing using the Fetch API.
The Fetch API allows you to asynchronously request for a resource. Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.
To intercept HTTP requests, use the webRequest API. This API enables you to add listeners for various stages of making an HTTP request. In the listeners, you can: Get access to request headers and bodies and response headers.
It allows you to make an HTTP request, i.e., either a GET request (for getting data) or POST request (for posting data). The basic fetch request can be explained by the following code: 1 2 3 4 5 6 7 8 9 10 11 12 fetch('url') . then(response => { //handle response console.
more complicated API, request and response concepts are mixed together. lacks streaming, whole response is going to buffer in memory, not available for binary data.
Since fetch
returns a promise, you can insert yourself in the promise chain by overriding fetch
:
(function () {
var originalFetch = fetch;
fetch = function() {
return originalFetch.apply(this, arguments).then(function(data) {
someFunctionToDoSomething();
return data;
});
};
})();
Example on jsFiddle (since Stack Snippets don't have the handy ajax feature)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With