最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - fetch and addEventListener - Stack Overflow

programmeradmin1浏览0评论

I read in 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'));

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'));
Share Improve this question asked Jun 8, 2017 at 16:00 Ryan RagleRyan Ragle 1411 gold badge1 silver badge6 bronze badges 3
  • 7 That's ServiceWorker code. No, it doesn't work in a normal window. – Bergi Commented Jun 8, 2017 at 16:01
  • how to listen in the normal window when fetch happens? – Prathamesh Rasam Commented Apr 24, 2018 at 18:52
  • Your response is here: developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/… – Mohammad Zare Moghadam Commented May 20, 2018 at 6:30
Add a comment  | 

1 Answer 1

Reset to default 34

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(actualFetch, that, args) {
        // Forward function call to the original fetch
        const result = Reflect.apply(actualFetch, 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.

发布评论

评论列表(0)

  1. 暂无评论