Server worker being registered twice

2k views Asked by At

I'm using FCM web notification service, when I am calling the register function:

if ('serviceWorker' in navigator) {
         window.addEventListener('load', function() {
        navigator.serviceWorker.register('/sw.js').then(function(registration) {
          // Registration was successful
          console.log('ServiceWorker registration successful with scope: ', registration.scope);
        }).catch(function(err) {
          // registration failed :(
          console.log('ServiceWorker registration failed: ', err);
        });
      });
    }

The service worker is registered twice, one because of this function, and one by the FCM script. This is my service worker code:

importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js');

    'messagingSenderId': '<my senderid>'
});

const messaging = firebase.messaging();


messaging.setBackgroundMessageHandler(function (payload) {
   
    
    self.addEventListener('notificationclick', function (event) {
        event.notification.close();

        var promise = new Promise(function (resolve) {
            setTimeout(resolve, 1000);
        }).then(function () {
            return clients.openWindow(payload.data.locator);
        });

        event.waitUntil(promise);
    });
   
    var notificationTitle = payload.data.title;
    var notificationOptions = {
        body: payload.data.body,
        icon: payload.data.icon
    };
    return self.registration.showNotification(notificationTitle,
        notificationOptions);
});

One more thing, when I send test notifications, and I click the first message and it opens the URL correctly, but in the same instance of Chrome, all other messages I click open the URL of the first message. This problem does not happen on Firefox, just Chrome. I am using chrome version 55

1

There are 1 answers

1
Matt Gaunt On BEST ANSWER

With the firebase messaging SDK you don't need to call register.

If you call register, you can make the SDK use your service worker by calling useServiceWorker() (See: https://firebase.google.com/docs/reference/js/firebase.messaging.Messaging#useServiceWorker)

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js')
    .then(function(registration) {
      messaging.useServiceWorker(registration);
    });
  });
}

The reason the SDK registers the service worker for you is that it sets a scope that will prevent it from interfering with any other service workers you might have.

Regarding your second issue, are you sending different URLs or are they the same URLs?