如何侦听所有提取API调用? [英] How to listen on all fetch API calls?

查看:38
本文介绍了如何侦听所有提取API调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以修改 XMLHttpRequest.prototype.open 来劫持所有Ajax请求.如果切换到新浏览器的访存API,该怎么做?

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

推荐答案

我不建议修改本机对象和函数(即使您使用 XMLHttpRequest.prototype.open 的方式)也是如此.但是您可以替换 fetch 函数itselt.最后,它只是一个功能.

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

这篇关于如何侦听所有提取API调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆