问题
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);
};
回答1:
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);
out.then(({ok}) => console.log('loaded', ok) )
return out;
}
}(window, window.fetch))
fetch('https://jsonplaceholder.typicode.com/users')
fetch('https://jsonplaceholder.typicode.com/userz')
来源:https://stackoverflow.com/questions/38995750/how-to-listen-on-all-fetch-api-calls