How can we use FCM Service Worker with a existing Service Worker?

Pranav C Balan picture Pranav C Balan · Jan 17, 2018 · Viewed 9.8k times · Source

We are creating a PWA web app and currently, we are using sw-precache library for generating service worker file, which is working as expected. And now we have added FCM service worker for listening incoming message while it's offline, but it's overwriting our existing service worker.

So how can we integrate the firebase service worker with an existing service worker which is generated using sw-precache?

I'd tried several ways, current code :

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/service-worker.js').then((registration) => {
        console.log('Service Worker registered');
    }).catch(function (err) {
        console.log('Service Worker registration failed: ', err);
    });

    navigator.serviceWorker.register('/firebase-messaging-sw.js', { scope: '/firebase-cloud-messaging-push-scope' }).then(function (registration) {
         console.log('f Service Worker registered');
     }).catch(function (err) {
         console.log('f Service Worker registration failed: ', err);
     });
}

UPDATE 1: I'd tried useServiceWorker(registration) as well, its registering the main service worker but when I'd initializing firebase within my service it's expecting the firebase-messaging-sw.js to load so it's throwing some error in console.

Service code:

import * as firebase from 'firebase';
import { isPlatformBrowser } from '@angular/common';

@Injectable()
export class MessagingService {   
  messaging;

  constructor(
    @Inject(PLATFORM_ID) private _platformId: Object, ) {
    if (isPlatformBrowser(this._platformId)) {
      var config = {
        messagingSenderId: "XXXXXXXX"
      };

      firebase.initializeApp(config);
      this.messaging = firebase.messaging();
    }
  }

  //  ......

}

Error in console :

enter image description here

enter image description here

Tried the following answer as well, but no success: https://stackoverflow.com/a/46171748/3037257


UPDATE 2: Finally adding useServiceWorker(registration) and an empty firebase-messaging-sw.js file both service workers are getting registered but caching is not working.

Answer

Tushar Acharekar picture Tushar Acharekar · Jan 17, 2018

In order to take all control of sw.js and push notification useServiceWorker is very useful.

See this documentation useServiceWorker(registration)

   /------index.html------/
    var config = {
        apiKey: "xxxxxxxxxxxx",
        authDomain: "xxxxxxxxxxxx",
        databaseURL: "xxxxxxxxxxxx",
        projectId: "xxxxxxxxxxxx",
        storageBucket: "xxxxxxxxxxxx",
        messagingSenderId: "xxxxxxxxxxxx"
    };
    firebase.initializeApp(config);
    var messaging = firebase.messaging();

navigator.serviceWorker.register('service-worker.js')
.then((registration) => {
  messaging.useServiceWorker(registration);


});