typescript - Angular prikaz push obavijesti u pozadini


Primam Firebase obavijesti i želim ih prikazati kao skočne obavijesti u pozadini (kad je korisnik na drugoj kartici).

U svom firebase-messaging-sw.js pokušao sam s dvije različite metode, obje koriste console.log() za ispis payloada, i to je u redu, ali ne pojavljuje se nikakva notifikacija u pozadini.

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

i

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

Također sam pokušao smanjiti verziju Firebasea, ali bez uspjeha. Dakle, kako mogu prikazati skočni prozor?

Odgovor #1

Prošlo je puno vremena otkako sam postavio ovo pitanje, pa se točno ne mogu sjetiti što je bio problem, ali sada radi pa ću ovdje ostaviti rješenje. Vidio sam ovo rješenje negdje, ali se ne mogu sjetiti gdje. Ako ga pronađem, stavit ću referencu.

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