Service Worker安装成功后更新UI

Tah*_*man 0 javascript service-worker progressive-web-apps

看起来Service Worker在工作线程上运行,并且无法访问DOM.但是,一旦安装了Service Worker,我希望我的用户知道应用程序现在可以脱机工作.我怎样才能做到这一点?

Viv*_*ngh 6

当服务工作者进入时activated state,这是展示吐司的最佳时间Content is cached for offline use.注册服务人员时,请尝试以下代码.

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);
  });
}
Run Code Online (Sandbox Code Playgroud)