Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register service worker after hard refresh

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

enter image description here

like image 912
Aleksandr Shumilov Avatar asked Mar 06 '23 17:03

Aleksandr Shumilov


1 Answers

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');
            });
          }
        });
      }
    }
like image 157
Durim Avatar answered Mar 09 '23 07:03

Durim