Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom code to Angular cli generated service worker

I can generate and config the service worker (by config file) generated by angular cli without issues. However there seems no documentation on how to add custom code the ngsw-worker.js, since i would like to add functions like push notification, post message etc. Wonder to plug in to the ngsw-worker.js

like image 461
Fan Cheung Avatar asked Mar 23 '18 04:03

Fan Cheung


2 Answers

You just need to create your own service worker file.

First, lets start by creating our own very basic service worker.

//my-service-worker.js

self.addEventListener('notificationclick', (event) => {
  console.log('notification clicked!')
});

Awesome, now in your App module change the service worker registration

//app.module.ts

ServiceWorkerModule.register('my-service-worker.js', { enabled: environment.production })

You will also need to add your service worker to your assets in your angular.json file

//angular.json

  "assets": {
  ...,
  "src/my-service-worker.js"
}

Great! Now you are all set, but we just lost all of the stuff that the angular service worker provides! Hang on, we’re not finished yet. Go back to your custom service worker and change it up

//my-service-worker.js

importScripts('./ngsw-worker.js');
self.addEventListener('notificationclick', (event) => {
  console.log('notification clicked!')
});

All Right! Now we have everything working, the angular cli accepting push notifications, and we can add our own fluff to the notification events!

https://medium.com/@smarth55/extending-the-angular-cli-service-worker-44bfc205894c

like image 187
Tahseen Quraishi Avatar answered Sep 30 '22 00:09

Tahseen Quraishi


You can subscribe to the messages in your app:

import { SwPush } from '@angular/service-worker';

this.SwPush.messages.subscribe(message => {
    console.log('[App] Push message received', message)
}

Check out this article: https://medium.com/google-developer-experts/a-new-angular-service-worker-creating-automatic-progressive-web-apps-part-2-practice-3221471269a1

like image 41
Stef Chäser Avatar answered Sep 30 '22 01:09

Stef Chäser