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 the learnt so far. and code change would 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 would take control.
So why we want to does is when there are 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 the event listener and status service worker has.
Once We register the service worker, it would return a Registerion object:
Navigation.serviceWorker.register ('/sw.js '). Then (function(reg) {//MethodReg.unregister (); Reg.update (); // State /*pointing to the Serviceworker object or is null*/reg.installing;//Start installing new service worker, if install faild then throw awayreg.waiting;//Service worker is a readyReg.activate;//The service worker is not a take over control //Have listener when update is foundReg.addeventlistener (' Updatefound ',function(){ //reg.installing is changed })})
Api:link
For the service worker itself:
var sw =// ... logs "Installing"/ /// "Installed" // "activating"/ /" avvtivated"// "redundant" Sw.addeventlistener (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 was no controller, then it means the data was loading from network:
if (! Navigator.serviceWorker.controller) { // page didn ' t load using a service workerbut 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 a update in progress, but update may fail // so we still need-track state change // Reg.installing.addEventLi Stener (' StateChange ', function () { Span style= "color: #0000ff;" >if (this . State = = "Installed" ) { // There is an update ready!
Otherwise, we listen ' Updatefound ', we track "Installing" state until it reach "installed" and then again we tell the user.
function () { Reg.installing.addEventListener() {() {if(this) . Satate = = "Installed") {// There is an update ready! } })})
[PWA] 9. Service Worker registerion && service work ' s props, methods and listeners