首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React & Service缓存的内容-通知用户

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

Stack Overflow用户
提问于 2017-12-19 07:13:34
回答 1查看 1.8K关注 0票数 4

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

建议告知用户缓存的内容或何时可用新内容,以便用户了解缓存的内容。

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

当我使用create-react-app时,在registerServiceWorker.js中有这样的代码:

此时,旧内容将被清除,新内容将被添加到缓存中。现在是显示“新内容可用;请刷新”的最佳时机。在你的网络应用中留言。

代码语言:javascript
复制
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,因为服务工作者远离脚本工作。我如何在一个反应组件中处理这个问题?

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-19 16:18:44

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

(在服务工作人员的上下文中运行的代码是独立的,您正确地知道,该代码没有访问DOM的权限。但这不是你要问的代码。)

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47881734

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档