Using Angular to create progressive web applications (PWA)
Angular is a great choice for developing PWA. Service Worker support has been included in Angular CLI since version 1.7.0
for a quick start on developing a PWA application . The Service Worker can be configured in the Angular application using the json configuration file, which provides many options and functions. Although it sounds great, there is one big disadvantage to using the Angular Service Worker — its logic cannot be extended in a standard way.
Why would you need to expand the capabilities of NGSW?
In my case, I needed to register a custom click notification event listener that would handle the click action of the push notification. I have to admit that the Angular Service Worker does an excellent job with receiving and displaying push notifications - this part is processed by the ngsw-worker.js file without any effort from the developer. And at first, it seemed that the only way to provide the work logic I needed was to make changes to the code of the generated ngsw-worker.js file when building the application. But I understood that this method is bad - it needs to be maintained and checked every time you make any changes to the ngsw configuration file. Fortunately, it turned out that the problem is easily solved by entering two additional files.
Decision
Let's start by creating two additional js files in the
/ src folder.
sw-custom.js is the file containing the event listener:')
(function () { 'use strict'; self.addEventListener('notificationclick', (event) => { event.notification.close(); console.log('notification details: ', event.notification); }); }());
sw-master.js is a file that combines NGSW with our own logic: importScripts('./ngsw-worker.js'); importScripts('./sw-custom.js');
Registration of assets
Having created new script files, we need to make sure that Angular takes them into account at build time. From a technical point of view, these are assets that are similar to the favicon.ico file created by Angular CLI when creating a project. We can register our additional resources in the angular.json file (.angular-cli.json for older Angular versions):
{ ..., "assets": [ "src/favicon.ico", "src/assets", "src/manifest.json", "src/sw-master.js", "src/sw-reminders.js" ], ... }
Re-register Service Worker script
The last step is to change the entry point to the Service Worker, which Angular registered during application startup. To do this, we need to change the ServiceWorkerModule.register entry in app.module.ts as follows:
ServiceWorkerModule.register('/sw-master.js', { enabled: environment.production })
We summarize
That's all, after the production assembly of the application, our new script files will be copied to the
/ dist folder and used by the application when registering the ServiceWorker. If you want to see more, you can also look at my GitHub profile, where I posted
an example of an Angular application with ServiceWorker , supplemented by custom logic.