Open PWA when clicking on push notification handled by service-worker ng7 + android

Though the provided solutions work, it will be nice to have an approach which does not modify service worker code in node_modules or the generated code.

The approach can be to create another script named custom-service-worker.js

In this file,

importScripts('./ngsw-worker.js');

(function () {
    'use strict';

    self.addEventListener('notificationclick', (event) => {
        console.log("This is custom service worker notificationclick method.");
        console.log('Notification details: ', event.notification);
        // Write the code to open
        if (clients.openWindow && event.notification.data.url) {
            event.waitUntil(clients.openWindow(event.notification.data.url));
        }
    });}
());

Register custom-service-worker.js as the service worker in place of ngsw-worker.js in the imports section where ServiceWorkerModule.register would be written.

Also don’t forget to add this script as asset in angular.json so that it gets copied in the dist folder.

I believe this approach saves us the hassle of doing anything extra to edit the original service worker file.

Leave a Comment

tech