Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 432
bijalcm Avatar asked Oct 27 '16 06:10

bijalcm


1 Answers

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:

  • firebase.google.com/docs/cloud-messaging/js/
  • web-push-book.gauntface.com
like image 147
Matt Gaunt Avatar answered Oct 20 '22 05:10

Matt Gaunt