Whenever the web application with service worker is reloaded after hard refresh (Ctrl + F5
for Chrome, for example), the service worker is unable to register afterwards.
According to the documentation at W3C
Note: navigator.serviceWorker.controller returns null if the request is a force refresh (shift+refresh). The ServiceWorker objects returned from this attribute getter that represent the same service worker are the same objects.
So, the question is: is it really impossible to register service worker right after the hard refresh is performed? I am checking the existence of the service worker with the navigator.serviceWorker.controller
. Please see the attached GIF which shows interaction with the https://googlechrome.github.io/samples/service-worker/basic/ page
Workaround solution for making service workers work even after hard reload is by unregistering and registering the service worker scripts through the code snippet below.
if ('serviceWorker' in navigator) {
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.getRegistration(navigator.serviceWorker.controller.scriptURL).then(function (sw) {
if (sw) {
sw.unregister().then(() => {
navigator.serviceWorker.register('service-worker.js');
});
}
});
} else {
const url = window.location.protocol + '//' + window.location.host + '/service-worker.js';
navigator.serviceWorker.getRegistration(url).then(function (sw) {
if (sw) {
sw.unregister().then(() => {
navigator.serviceWorker.register('service-worker.js');
});
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With