When the Refersh button was clicked, we need to tell the waiting service worker to replace the current service worker right Away. Then we refresh the page load the latest cache from the new cache db.
There is three new components to help:
Service worker can all skipwaiting () while it is "waiting" or "installing".
Self.skipwaiting ()
Then the waiting service worker should take over right away.
So we want to call it function when user click on the Refresh button in the notification.
Then what can we send the signal from our page to waiting Servcie worker?
// From a page:reg.installing.postMessage ({foo: ' Bar '}); // In the service worker: function (event) { // {foo: ' Bar '}})
The page gets event when the value chanages, means a new service worker take over, we'll use this as a signal to reload Our page:
function () { // Navigator.serviceWorker.controller has changed})
--------------------------------------------------------
Our page: Send single to service worker ask it to reload:
function (worker) { varthis. _toastsview.show ("New version available", { buttons: [ ' Refresh ', ' dismiss '] }); Toast.answer.then (function(answer) { if (answer! = ' Refresh ') { // Tell the service worker to skipwaiting Worker.postmessage ({message: ' Skipwaiting '}} );};
Service worker: Listen to the message event and call Skilwaiting ():
// Todo:listen for the ' message ' event, and call // skipwaiting If you get the appropriate message function (event) { if(event.data.message = = "Skipwaiting") { self.skipwaiting (); }})
The on We page, listen to Controllerchange event, Insdie load the page:
Indexcontroller.prototype._registerserviceworker =function() { if(!navigator.serviceworker)return; varIndexcontroller = This; Navigator.serviceWorker.register ('/sw.js '). Then (function(reg) {if(!Navigator.serviceWorker.controller) {return; } if(reg.waiting) {indexcontroller._updateready (reg.waiting); return; } if(reg.installing) {indexcontroller._trackinstalling (reg.installing); return; } reg.addeventlistener (' Updatefound ',function() {indexcontroller._trackinstalling (reg.installing); }); //Todo:listen for the controlling service worker changing //and reload the pageNavigator.serviceWorker.addEventListener (' Controllerchange ',function() {window.location.reload (); }) });};
[PWA] 10. Trigger a version update