Angular Service worker with FCM push notification

2019-06-27 04:40发布

问题:

In my web app(using Angular4) I am using "@angular/service-worker": "^1.0.0-beta.16" for generating service worker and also using firebase-messaging-sw.js for FCM push notification, angular/service-worker creates worker-basic.min.js only in production build. Now, how to use these 2 service-workers together??

回答1:

I can respond about using simultaneously :

  • sw-precache Service Worker (whose aim is to cache static ressources) implemented as service-worker.js. See https://coryrylan.com/blog/fast-offline-angular-apps-with-service-workers

  • Firebase Messaging Service Worker (whose aim is to handle web push notifications) implemented as firebase-messaging-sw.js.

1. Development: in src directory:

  • I create an empty file named service-worker.js. The real one will be generated after the build process but this file has to exist (even empty) to avoid error message while serving with ng serve.
  • I create a file named firebase-messaging-sw.js whose content is: (add https:// before both www, stakoverflow limits me in number of links!)

    importScripts('www.gstatic.com/firebasejs/3.9.0/firebase-app.js'); importScripts('www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js'); firebase.initializeApp({ 'messagingSenderId': 'xxxxxxxxxxxx' // replace by yours! }); const messaging = firebase.messaging();
  • I create a file named global-sw.js. This is THE Service Worker you have to register in index.html (ask me how if needed). Content of global-sw.js is:

    importScripts('service-worker.js'); importScripts('firebase-messaging-sw.js');

2. Update of .angular-cli.json: To have those files included in my future dist directory (generated with the production build process), I update .angular-cli.json this way : .angular-cli.json - extract

3. Production build: I run ng build -prod then I generate service-worker.js. For me, this one can only be generated after the build process.



回答2:

The SWPrecacheWebpackPlugin wrapper for the swprecache module's API has an option called "importScripts" which can be used to import for example "firebase-messaging-sw.js" in this case.