We can modify the XMLHttpRequest.prototype.open
to hijack all Ajax requests before. What's the equivalent if switching to the new browser's fetch API?
const originalRequestOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
this.addEventListener('load', function() {
// do something
});
originalRequestOpen.apply(this, arguments);
};
I don't recommend to modify native objects and functions (even the way you did with XMLHttpRequest.prototype.open
). But you can replace fetch
function itselt. In the end it is just a function.
(function(ns, fetch) {
if (typeof fetch !== 'function') return;
ns.fetch = function() {
var out = fetch.apply(this, arguments);
// side-effect
out.then(({ ok }) => console.log('loaded', ok));
return out;
}
}(window, window.fetch))
fetch('https://jsonplaceholder.typicode.com/users')
fetch('https://jsonplaceholder.typicode.com/userz')
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