Reputation: 2973
I am using React+Service Worker+offline-plugin to create a Service Workerwith persistent caching for the website.
I want to tell the user when a new version is stored in cach and suggest to refresh the page but I don't know how to reference the Service Workerand what event I should listen to (Service Workeris created automatically by npm "offline-plugin").
Standard flow today:
New flow should be:
Upvotes: 6
Views: 6456
Reputation: 4993
You should look at the following link: Service Worker life cycle - updates
You can also update your service worker manually by running something like:
navigator.serviceWorker.register('/sw.js').then((reg) => {
// sometime later…
reg.update();
});
You can tell that you have a new version ready (and not yet activated) on the Service Worker's install
event.
You know that you have a new version loaded in the handler of the service worker's activate
event.
Upvotes: 1
Reputation: 5292
Service worker is a specialized form of a webworker.
When you registry a sw, like for example in serviceWorkerRegistry.js, you'll have access to several events.
e.g.
serviceWorkerRegistry.js:
if (!navigator.serviceWorker) return;
navigator.serviceWorker.register('/sw.js').then(function(reg) {
if (!navigator.serviceWorker.controller) {
return;
}
if (reg.waiting) {
console.log("inside reg.waiting");
return;
}
if (reg.installing) {
console.log("inside reg.installing");
return;
}
reg.addEventListener('updatefound', function() {
console.log("inside updatefound");
let worker = reg.installing;
worker.addEventListener('statechange', function() {
if (worker.state == 'installed') {
console.log('Is installed');
// Here you can notify the user, that a new version exist.
// Show a toast view, asking the user to upgrade.
// The user accepts.
// Send a message to the sw, to skip wating.
worker.postMessage({action: 'skipWaiting'});
}
});
});
});
sw.js:
// You need to listen for a messages
self.addEventListener('message', function(event) {
if (event.data.action === 'skipWaiting') {
self.skipWaiting();
}
});
Now the problem with offline plugin, is that it creates the sw for you, and in that way is harder to understand what the sw is doing.
I would say, it's better to create your own sw, this way you can understand better the functionality. this plugin can help you with the cache.
Upvotes: 5