获取并添加事件监听器

Rya*_*gle 9 javascript ajax google-chrome fetch

我在https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Response_objects中读到,您可以使用 addEventListener 在发生提取时触发。

我正在玩它,但我无法让它点火。这是代码。我也在使用 Chrome

addEventListener('fetch', event => alert('test'));
Run Code Online (Sandbox Code Playgroud)

a c*_*cat 28

您示例中的事件fetch仅在 Service Worker 中触发。当发生提取时,普通网页上不会触发任何内置事件。

但是,您可以挂钩全局获取函数,以便它执行您想要的操作。

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

每次获取完成时,这都会打印到控制台。

  • 我现在就给你加200票,干杯:) (2认同)