[PWA] 9. Service worker registerion && service work's props, methods and listeners
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[PWA] 9. Service worker registerion && service work's props, methods and listeners相关的知识,希望对你有一定的参考价值。
In some rare cases, you need to ask user to refresh the browsser to update the version. Maybe because some secrity issues.
As we have learnt so far. And code change will generate a new service work in the waiting list. Unitl the current service worker completely die (hard refresh or close the window). Then the new service work will take control.
So what we want to do is when there is a new service work ready, we want to notify user that he or she need to refresh the browser to update the appliation version.
First, let‘s see what kinds of event listener and status service worker has.
Once we register the service worker, it will return a registerion object:
navigation.serviceWorker.register(‘/sw.js‘).then(function(reg) { // method reg.unregister(); reg.update(); // state /* Pointing to the serviceWorker object or be null */ reg.installing; // start installing new service worker, if install faild then throw away reg.waiting; // service worker is ready to take over reg.activate; // service worker is not take over control // has listener when update is found reg.addEventListener(‘updatefound‘, function(){ // reg.installing is changed }) })
API: Link
For the service worker itself:
var sw = reg.installing; console.log(sw.state); // ...logs "installing" // state can also be: // "installed" // "activating" // "avvtivated" // "redundant" sw.addEventListener(‘statechange‘, function(){ // sw.state has changed })
Aslo about:
naviagetor.serviceWorker.controller
"navigator.serviceWorker.controller" refer to the service worker that controls the page.
So if there is no controller, then it means the data is loading from network:
if(!navigator.serviceWorker.controller){ // page didn‘t load using a service worker but from network }
Otherwise we need to look for registration.
If there is a "waiting" worker:
if(reg.waiting){ // there is a update ready! Notify user }
Else If there is a "installing" worker:
if(reg.installing){ // there is an update in progress, but update may fail // So we still need to track state change // if it reached installed statue, then notify user reg.installing.addEventListener(‘statechange‘, function(){ if(this.state == "installed"){ // there is an update ready! } }) }
Otherwise, we listen ‘updatefound‘, we track "installing" state until it reach "installed", then again we tell the user.
reg.addEventListener(‘updatefound‘, function(){ reg.installing.addEventListener(‘statechange‘, function(){ if(this.satate == "installed"){ // there is an update ready! } }) })
以上是关于[PWA] 9. Service worker registerion && service work's props, methods and listeners的主要内容,如果未能解决你的问题,请参考以下文章
@vue/cli-plugin-pwa 没有创建 service-worker.js
Webpack之(progressive web application) - PWA中的 Service Workers 是什么