Reputation: 2081
I'm building a PWA and I'm looking for a way to update a service worker when the app is already open and loaded.
For example the user opens the app once on his phone and then switches through other apps during the day without completely closing the PWA.
If I upload a new version in between, how can the service worker then be updated?
And also is there maybe a way to notify the service about an update while the user is using the App?
Is the service worker able to automatically check from time to time if something new was uploaded? The whole app is cached and served from a s3 bucket.
Any advice would be greatly appreciated.
Upvotes: 2
Views: 1326
Reputation: 6872
From MDN on "ServiceWorkerRegistration.update() ".
The update method of the ServiceWorkerRegistration interface attempts to update the service worker. It fetches the worker's script URL, and if the new worker is not byte-by-byte identical to the current worker, it installs the new worker. The fetch of the worker bypasses any browser caches if the previous fetch occurred over 24 hours ago.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw-test/sw.js', {scope: 'sw-test'}).then(function(registration) {
// registration worked
console.log('Registration succeeded.');
button.onclick = function() {
registration.update();
}
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
};
Upvotes: 2