Angular show push notifications in background

Viewed 339

I'm receiving firebase notifications and I want to display them as a pop up notification in background (when user is on different tab).

In my firebase-messaging-sw.js I have tried with two different methonds, both of them are console.log() the payload, and that's okay, but there is no notification pop up in the background.

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);
});

and

messaging.onBackgroundMessage((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'
  };

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

I have tried also to downgrade firebase, but no success. So, how can I display pop up ?

1 Answers

It's been a long time since I posted this question, so I can't remember exactly what the problem was, but it's working now so I'll leave the solution here. I saw this solution somewhere, but I can't remember where. if I find it, I'll put a reference.

const messaging = firebase.messaging.isSupported() ? firebase.messaging() : null;

if ('serviceWorker' in navigator) {
  console.log('Registering service worker...')
  navigator.serviceWorker.register('firebase-messaging-sw.js')
    .then(function (registration) {
      console.log('Service Worker Registered');
      console.log(registration)
    })
    .catch(function (err) {
      console.log('error', err)
    });

};

messaging.onBackgroundMessage((payload) => {
  self.clients.matchAll({
    type: 'window',
    includeUncontrolled: true
  }).then(function (clients) {
    clients.forEach(function (client) {
      client.postMessage(payload);
    });
  });

});

self.addEventListener('push', event => {
  const promiseChain = isClientFocused()
    .then((clientIsFocused) => {
      if (clientIsFocused) {
        console.log('Don\'t need to show a notification.');
        return;

      }

      // Client isn't focused, we need to show a notification.
      const messageFrom = event.data.json().data.event;

      const promiseNotify = registration.getNotifications()
      .then(notifications => {
        let currentNotification;
  
        for (let i = 0; i < notifications.length; i++) {
          console.log(notifications[i].data)
          if (notifications[i].data &&
            notifications[i].data.messageFrom === messageFrom) {
            currentNotification = notifications[i];
          }
        }
  
        return currentNotification;
      })
      .then((currentNotification) => {
        let notificationTitle;
        const options = {
          icon: './assets/img/logo.png'
        }
  
        if (currentNotification) {
          // We have an open notification, let's do something with it.
          const messageCount = currentNotification.data.newMessageCount + 1;
          let body = '';
          switch (messageFrom) {
            case NotificationEvent.VEHICLE_IMPORTED:
              body = `${messageCount} vehicles has finished importing.`;
              break;
            // create cases if needed  
          }
          options.body = body;
          options.data = {
            messageFrom: messageFrom,
            newMessageCount: messageCount
          };
          notificationTitle = `New Images`;
  
          // Remember to close the old notification.
          currentNotification.close();
        } else {
          let body = '';
          switch (messageFrom) {
            case NotificationEvent.VEHICLE_IMPORTED:
              body = 'Vehicle has finished importing.'
              break;
            // create cases if needed
          }
          options.body = body;
          options.data = {
            messageFrom: messageFrom,
            newMessageCount: 1
          };
          notificationTitle = `Catch`;
        }
  
        return registration.showNotification(
          notificationTitle,
          options
        );
      });
      return promiseNotify
    });


  event.waitUntil(promiseChain);
})

function isClientFocused() {
  return clients.matchAll({
    type: 'window',
    includeUncontrolled: true
  }).then((windowClients) => {
    let clientIsFocused = false;

    for (let i = 0; i < windowClients.length; i++) {
      const windowClient = windowClients[i];
      if (windowClient.focused) {
        clientIsFocused = true;
        break;
      }
    }

    return clientIsFocused;
  });
}
Related