Register own Service Worker on Angular alongside its own worker

We've added custom logic along-side the Angular Service Worker by using a simple intermediary script to load both the generated ngsw script and our own custom script. This plays well with the Angular build process.

app.module.ts

@NgModule({
  //...
  imports: [
    ServiceWorkerModule.register('sw-master.js', {
      enabled: environment.production
    }),
    //...
  ],
  //...
});

angular.json

...
"assets": [
  ...
  "src/manifest.json",
  "src/sw-custom.js",
  "src/sw-master.js"
],...

sw-master.js

importScripts('./ngsw-worker.js'); // generated by Angular build process
importScripts('./sw-custom.js');

sw-custom.js

Just an example... we were making it so users could click on push notifications and be directed to a particular app view.

(function () {
  'use strict';
  self.addEventListener('notificationclick', (event) => {
    event.notification.close();
    if (clients.openWindow && event.notification.data.url) {
      event.waitUntil(clients.openWindow(event.notification.data.url));
    }
  });
}());