Service Worker安装成功后更新UI [英] Update UI when Service Worker installed successfully

查看:92
本文介绍了Service Worker安装成功后更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来Service Worker在工作者上下文中运行,并且无法访问DOM。但是,一旦安装了Service Worker,我希望我的用户知道应用程序现在可以脱机工作。我该怎么办?

Looks like Service Worker runs in a worker context and has no access to the DOM. However, once Service Worker installed, I want my users to know that the app will now work offline. How can I do that?

推荐答案

当服务工作者处于激活状态时,这是显示吐司的最佳时间'内容被缓存以供离线使用'。在注册服务工作者时尝试以下代码。

When the Service Worker is in activated state, this is the perfect time to display the toast 'Content is cached for offline use'. Try something below code while registering your service worker.

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js').then(function(reg) {
    // updatefound is fired if service-worker.js changes.
    reg.onupdatefound = function() {
      var installingWorker = reg.installing;

      installingWorker.onstatechange = function() {
        switch (installingWorker.state) {
          case '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 the page's interface.
              console.log('New or updated content is available.');
            } 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 now available offline!');
            }
            break;

          case 'redundant':
            console.error('The installing service worker became redundant.');
            break;
        }
      };
    };
  }).catch(function(e) {
    console.error('Error during service worker registration:', e);
  });
}

这篇关于Service Worker安装成功后更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆