How to listen on all fetch API calls?

两盒软妹~` 提交于 2020-12-09 23:46:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!