Service Worker showing as deleted after reloading the page

Viewed 309

Am using react and trying to implement service worker, I had written a mini service worker file for push notifications, when the user clicks a button am registering a service worker, now if i send a push message it working as expected, but when i reload the page, the service worker in application shows as deleted even though the registration was successful, please refer screenshot

Service worker code

    const self = this;

    function receivePushNotification(event) {
      console.log('[Service Worker] Push Received.');
      console.log(event);

      // const { image, tag, url, title, text } = event.data.json();

      const options = {
        data: '/neworders',
        body: 'New order request',
        vibrate: [200, 100, 200],
        badge: 'https://spyna.it/icons/favicon.ico',
        actions: [
          {
            action: 'Detail',
            title: 'View',
            icon: 'https://via.placeholder.com/128/ff0000',
          },
        ],
      };
      event.waitUntil(self.registration.showNotification('Hello', options));
    }

    function openPushNotification(event) {
      console.log(
        '[Service Worker] Notification click Received.',
        event.notification.data
      );

      event.notification.close();
      event.waitUntil(clients.openWindow(event.notification.data));
    }

    self.addEventListener('install', function (event) {
      console.log({ event });
      // The promise that skipWaiting() returns can be safely ignored.
      self.skipWaiting();

      // Perform any other actions required for your
      // service worker to install, potentially inside
      // of event.waitUntil();
    });

    self.addEventListener('activate', (event) => {
      console.log('V1 now ready to handle fetches!');
    });
    self.addEventListener('push', receivePushNotification);
    self.addEventListener('notificationclick', openPushNotification);

Register service worker function

function registerServiceWorker() {
  return navigator.serviceWorker.register('/newsw.js');
}

Service worker deleted screenshot

Service worker deleted screenshot

2 Answers

I suspect it happens because you turned "update on reload" on.

This forces the service worker to update whenever you reload the page. (read more here)

I know its been a while but reached here having the same issue and in my case it was a timing problem, I'm just starting to understand service workers so I came up writing a unregister/register script on my test page like

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistrations().then(regs=>regs.map(r=>r.unregister()))
    navigator.serviceWorker.register("/modules/service-worker.js")
}

if you look closely, getRegistrations returns a promise so the code inside then (the inregistration) may not run just before the register line, in my case, very strangely (sorry for my english) it alternates when reloading, once deleted, once running. I solved thid by moving the registration inside the chain like:

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.getRegistrations().then(regs=>{
        regs.map(r=>r.unregister())
        navigator.serviceWorker.register("/modules/service-worker.js")
    })
}

(btw its my first answer :D)

Related