2016-05-14 67 views
0

上周我一直在使用Service Worker,目前安装了用于脱机缓存文件和推送通知的优秀安装。显示服务工作人员状态的消息

还有最后一两件事,我希望能够以显示对服务人员的某些状态的UI消息,目前我对激活状态下面的代码:

if ('serviceWorker' in navigator) { 
navigator.serviceWorker.addEventListener('controllerchange',function(event) { 
    navigator.serviceWorker.controller.addEventListener('statechange', function() { 
if (this.state === 'activated') { 
    document.getElementById('offlineNotification').classList.remove('hidden'); 
} 
}); 
}); 
} 

现在我想为安装状态创建一条消息,允许我显示类似于“脱机服务正在更新”的消息,如果有人正在处理此问题并知道如何操作,请告诉我。

我已经尝试过同样的代码,但与 “如果(this.state === '安装')”

“如果(this.state === '安装'”

既不似乎工作。

回答

2

服务工作者有一个生命周期是从你的网页完全分开的。 要安装服务人员为您的网站,你需要注册。

self.addEventListener('install', function(event) { 
    // Perform install steps 
}); 

当我们安装后,激活步骤将随之而来,这是处理旧缓存管理的好机会。

self.addEventListener('activate', function(event) { 
    // Perform activate steps, Typically cache management. 
}); 

激活步骤后,服务人员将控制在其范围下跌的所有页面,但直到它再次加载已注册的第一次服务工作者的页面将无法控制。

一旦服务人员处于控制之下,它将处于以下两种状态之一:either the service worker will be terminated以节省内存,或it will handle fetch and message events发生在网页请求或消息从您的页面发出时。 您也可以尝试像,

if ('serviceWorker' in navigator) { 
     navigator.serviceWorker.register('/sw.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." 
        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); 
     }); 
    } 
+0

正如我在OP中所说的,我已经知道如何安装服务人员,并且我已经有一名服务人员安装,我不需要编写代码。我需要的是在UI中显示更新通知的一种方式(IE:不是控制台日志,实际网页),就像您在OP中所述的那样,您可以激活它。 – NGriffin

+0

区分更新与首次安装正是我所需要的'navigator.serviceWorker.controller'检查。谢谢! – salbahra

0

看看在live flowchart demo上ServiceWorker食谱,并在使用电报通知用户当有更新的code snippet

+0

出于某种原因,您上面链接的页面不会在我的手机甚至iPad上滚动。 – marvindanig

+1

我在ServiceWorker Cookbook repo中提交了一个问题(https://github.com/mozilla/serviceworker-cookbook/issues/254)。如果可以,请添加更多的细节问题。 – Marco