How to get push message events like click,close,show with firebase cloud messaging

bijalcm picture bijalcm · Oct 27, 2016 · Viewed 10.4k times · Source

Trying to implement web push notifications using FCM.

I am able to receive push message with payload on browser using firebase cloud messaging library.

Below is a javascript code snippet.

<script src="https://www.gstatic.com/firebasejs/3.5.1/firebase.js">  </script>
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.onMessage(function(payload){
    console.log('onMessage',payload);
});

How to capture events like click,close,show,etc ?

Answer

Matt Gaunt picture Matt Gaunt · Oct 31, 2016

Notification Open

You can listen for notification clicks for Data payloads by adding the following to your firebase-messaging-sw.js file:

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

  // Do something as the result of the notification click
});

Notification Close

You can listen for notification close events with:

self.addEventListener('notificationclose', function(event) {
  // Do something as the result of the notification close
});

Note: event.waitUntil()

You should be aware that to ensure you code has time to complete running, you need to pass a promise into event.waitUntil() that resolves when your code is finished, for example:

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

  const myPromise = new Promise(function(resolve, reject) {
    // Do you work here

    // Once finished, call resolve() or  reject().
    resolve();
  });

  event.waitUntil(myPromise);
});

You'll know when the notification is shown if it's a data payload because you need to call self.registration.showNotification() in your own code, like so:

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
      notificationOptions);
});

You can't detect when a notification is displayed for a "notification" payload as the SDK handles both displaying the notification and behavior when it's clicked.

Code snippets from: