Badge Not Displayed on iOS PWA Despite Receiving Push Notifications

20 Views Asked by At

I'm working on a Progressive Web App (PWA) with Firebase for push notifications. My goal is to display a badge for unread messages on the app icon when notifications are received, using the service worker.

Here's the of my service worker code:

importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js');

const firebaseConfig = {
    apiKey: "...",
    authDomain: "...",
    projectId: "...",
    storageBucket: "...",
    messagingSenderId: "...",
    appId: "...",
    measurementId: "..."
    };

let badgeCount = 0;

console.log('worker: [firebase-messaging-sw.js] Loaded');

firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
  console.log('worker: [firebase-messaging-sw.js] Received background message ', payload);
  badgeCount++; // Increment badge count for each message
  if (navigator.setAppBadge) {
      navigator.setAppBadge(badgeCount).catch((error) => {
          console.error('Error setting badge:', error);
      });
  }

  const notificationTitle = payload.notification.title;
  const notificationOptions = {
      body: payload.notification.body,
  };
  return self.registration.showNotification(notificationTitle, notificationOptions);
});

self.addEventListener('notificationclick', function (event) {
  // Handle notification click event here
  console.log('Notification clicked:', event);
});

self.addEventListener('notificationclose', function (event) {
  // Handle notification close event here
  console.log('Notification closed:', event);
});

Notifications are successfully received, but the badge count does not display on iOS devices (tested only on iOS). If I set the app badge directly to 99 this also works. I think the"onBackgroundMessage" is not called if I recive a web push.

What is the corret way to do this?

0

There are 0 best solutions below