zl程序教程

您现在的位置是:首页 >  其他

当前栏目

[PWA] 9. Service worker registerion && service work's props, methods and listeners

amp and &# 39 Service work Worker Props
2023-09-14 09:00:53 时间

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!
        }
    })
})