【问题标题】:React & Service Worker - Cached Content - Inform userReact & Service Worker - 缓存内容 - 通知用户
【发布时间】:2017-12-19 07:13:34
【问题描述】:

我对@9​​87654321@ 和reactjs 有疑问。

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

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

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

此时,旧内容将被清除,并且 新内容将被添加到缓存中。这是完美的 是时候显示“新内容可用;请刷新”。 在您的网络应用中发送消息。

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,因为服务工作者远离脚本工作。 如何在反应组件中处理这个问题?

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

【问题讨论】:

    标签: reactjs caching service-worker create-react-app


    【解决方案1】:

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

    (有单独的代码在服务工作者的上下文中运行,您是正确的,该代码无权访问 DOM。但这不是您要询问的代码。)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 2017-05-27
    • 2018-05-14
    • 1970-01-01
    相关资源
    最近更新 更多