Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen on all fetch API calls?

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);
};
like image 757
Ivor Zhou Avatar asked Aug 17 '16 11:08

Ivor Zhou


1 Answers

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')
like image 161
Yury Tarabanko Avatar answered Oct 18 '22 16:10

Yury Tarabanko