Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I read in https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Response_objects that you can use addEventListener to trigger when a fetch happens.

I'm playing with it, and I can't get it to fire. Here's the code. I'm also using Chrome

addEventListener('fetch', event => alert('test'));

The fetch event in your example only fires in a Service Worker. There is no built-in event that is fired on a normal webpage when a fetch happens.

However, you could hook the global fetch function so it does what you want.

window.fetch = new Proxy(window.fetch, {
    apply(fetch, that, args) {
        // Forward function call to the original fetch
        const result = fetch.apply(that, args);
        // Do whatever you want with the resulting Promise
        result.then((response) => {
            console.log("fetch completed!", args, response);
        return result;

This would print to the console every time a fetch is completed.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.