1

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?

tony19
  • 125,647
  • 18
  • 229
  • 307
Sudarsan GP
  • 1,194
  • 14
  • 22

1 Answers1

0

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.

Arnelle Balane
  • 5,437
  • 1
  • 26
  • 32