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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With