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

11,911

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:

Share:
11,911
bijalcm
Author by

bijalcm

Python, Django, Node.js, AWS

Updated on June 09, 2022

Comments

  • bijalcm
    bijalcm almost 2 years

    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 ?

  • Ketha Kavya
    Ketha Kavya over 7 years
    How to close a notification after 2seconds when i am using firebase?
  • Matt Gaunt
    Matt Gaunt over 7 years
    You can't do that with the web platform.
  • Yash Kadiya
    Yash Kadiya over 2 years
    self.addEventListener('notificationclick', function(event) {}); is not called when i click on notification.