使用工作箱中的 StaleWhileRevalidate 和 BroadcastUpdatePlugin,如何通知客户没有变化?

using StaleWhileRevalidate and BroadcastUpdatePlugin from workbox, how to notify clients of no change?

我使用 workbox 中的 StaleWhileRevalidate 和 BroadcastUpdatePlugin 并且它有效,当来自服务器的数据与缓存数据不同时,我的网页会收到通知。 当它们相同时获得通知的最简单方法是什么? 谢谢 嘉宝

对于实现 cacheDidUpdate() callback 的自定义 Workbox 插件来说,这将是一个很好的用例,而不是使用 BroadcastUpdatePlugin

(Under the hood, BroadcastUpdatePlugin 也实现了 cacheDidUpdate()。)

您将需要复制一些在使用 BroadcastUpdatePlugin 时“免费”获得的逻辑,但代码不会太多。

类似于:

const myPlugin = {
  cacheDidUpdate: async ({cacheName, request, oldResponse, newResponse}) => {
    // Use whatever combination of last-modified, etag, or other header to check.
    const isSame = oldResponse.headers.get('last-modified') ===
                   newResponse.headers.get('last-modified');
    const type = isSame ? 'CACHE_NOT_UPDATED' : 'CACHE_UPDATED';
    const message = {
      type,
      payload: {
        cacheName,
        url: request.url,
      }
    };

    const windows = await self.clients.matchAll({type: 'window'});
    for (const win of windows) {
      win.postMessage(message);
    }
  },
};

然后您可以将 myPlugin 添加到您想要的任何 workbox-strategies