admin管理员组

文章数量:1290295

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

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);
};
Share Improve this question asked Aug 17, 2016 at 11:46 Ivor ZhouIvor Zhou 1,27314 silver badges22 bronze badges 1
  • Patch fetch function? – Yury Tarabanko Commented Aug 17, 2016 at 11:53
Add a ment  | 

1 Answer 1

Reset to default 9

I don't remend 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./users')
fetch('https://jsonplaceholder.typicode./userz')

本文标签: javascriptHow to listen on all fetch API callsStack Overflow