Detect click on notification in web starter kit

315 Views Asked by At

I am using Google Web Starter kit and notification can be shown using service worker.

navigator.serviceWorker.getRegistration().then(function(reg) {
    var options = {
      body: body
    };
    reg.showNotification(title, options);
});

I would like to detect notificationclick event using the service worker.

notification behaviour article states that:

To achieve this we need to add a 'notificationclick' event listener to our service worker.

I tried the following:

navigator.serviceWorker.addEventListener('notificationclick', function() {
  console.log('notificationclick event called');
});

But it doesn't seem to work. Where should the event listener be added?

1

There are 1 best solutions below

0
Arnelle Balane On

You need to put the notificationclick event handler inside the service worker file, and use self.addEventListener (or just addEventListener):

# sw.js

self.addEventListener('notificationclick', function() {
  console.log('notificationclick event called');
});

Putting it in the service worker file makes sense because if the page/browser is closed, you'd still want the event handler to execute.