简体   繁体   中英

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

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

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

Starting with Angular8 I've found a way to use the worker-plugin to compile custom ServiceWorker code:

Prerequisites:

  • Angular8
  • Enable Service Workers in Angular ( "serviceWorker": true , etc)
  • Enable WebWorkers in Angular ( "webWorkerTsConfig": "src/tsconfig.workers.json" )

See: Angular: Using TypeScript for Service Worker (ServiceWorkerModule)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM