9

I'm using the recently release FCM messaging support for push notifications on the chrome. When my app is in the background, I get the notification but nothing happens when I click the notification. How to I specify the URL which should open when the user clicks the notification? (I understand how its done using the pure service worker concept using the notificationclick event, I want to know how to do that using FCM messaging.)

messaging.setBackgroundMessageHandler(function(payload) {
  var data = payload || {};
  var shinyData = decoder.run(data);

  console.log('[firebase-messaging-sw.js] Received background message ', shinyData);

  return self.registration.showNotification(shinyData.title, {
    body: shinyData.body,
    icon: shinyData.icon
  })
});

What am I missing here?

Vibgy
  • 577
  • 6
  • 15

2 Answers2

15

click_action is not one of the possible parameters of the showNotification function.

To handle the click on the notification, define a notificationclick event handler.

For example:

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  event.waitUntil(self.clients.openWindow(YOUR_URL_HERE));
});
Marco Castelluccio
  • 10,152
  • 2
  • 33
  • 48
  • I updated my question to make it more clear. I understand how to do that using the notificationClick event, but I dont know how to do that using the firebase messaging library. Sorry for the confusion. – Vibgy Oct 24 '16 at 01:50
  • I'm struggling with this response... what does 'self' refer to in this context? Is it the notification, the service worker registration or some other object entirely? – jcaruso Aug 29 '17 at 18:47
  • 4
    To answer my previous comment, the `self.addEventListener` should go in the script you provide when registering the service worker. The reason it wasn't working for me was because my script was being cached. I needed to unregister my service worker, ensure the script was no longer cached and then re-register the service worker. – jcaruso Aug 29 '17 at 19:18
10

Marco's answer is correct.

The Firebase Messaging Library is a wrapper on top of the Web Push API.

The notification: { click_action: 'https://...' } payload will show a notification and handle the click for you. To achieve the same with data payload you should implement the notificationclick event listener (Like Marco suggested).

self.addEventListener('notificationclick', function(event) {
  event.notification.close();

  ... Do your stuff here.
});

You can also do the same with the notificationclose event:

self.addEventListener('notificationclose', function(event) {
  ... Do your stuff here.
});
Matt Gaunt
  • 9,434
  • 3
  • 36
  • 57