React & Service Worker - 缓存内容 - 通知用户

React & Service Worker - Cached Content - Inform user

我有一个关于 service workersreactjs 的问题。

建议是通知用户有关缓存内容或新内容可用时,以便用户了解缓存内容。

我现在的问题是,我该如何通知用户?

当我使用 create-react-app 时,在 registerServiceWorker.js 中有这段代码,上面写着:

At this point, the old content will have been purged and the fresh content will have been added to the cache. It's the perfect time to display a "New content is available; please refresh." message in your web app.

function registerValidSW(swUrl) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the old content will have been purged and
              // the fresh content will have been added to the cache.
              // It's the perfect time to display a "New content is
              // available; please refresh." message in your web app.
              console.log('New content is available; please refresh.');
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log('Content is cached for offline use.');
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

但实际上在这个脚本上,当然,我无法访问 document,因为 service worker 在脚本之外工作。 我如何在 React 组件中处理这个问题?

其他人如何处理这个问题并通知用户?

您问题中包含的代码在 window 客户端的上下文中运行。您可以完全控制显示任何您想要的 UI 元素。请随意修改这些 console.log() 语句并改为显示一些内容。

(在 service worker 的上下文中运行了单独的代码,你是正确的,该代码无法访问 DOM。但这不是你要问的代码.)