reactjs - Firebase Foreground Notification Not Working in Next JS - Stack Overflow

admin2025-04-10  0

I've setup a firebase notification for my NextJS application, the following is the service worker code:

importScripts('.9.1/firebase-app.js');
importScripts('.9.1/firebase-messaging.js');

if (!firebase.apps.length) {
  firebase.initializeApp({...});

  firebase.messaging();

  firebase.messaging().setBackgroundMessageHandler(payload => {
    const notification = payload.data;

    const notificationTitle = notification.title;
    const notificationOptions = {
      icon: '/android-chrome-512x512.png',
      body: notification.body,
      data: notification,
    };

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

  self.addEventListener('notificationclick', function (event) {
    console.log('Notification clicked:', event.notification);

    event.notification.close();
    event.waitUntil(clients.openWindow(event.notification.data.redirectLink));
  });
}

The problem is that the background push notification works, but foreground notification does not works. Below is the code that I am using for handling the foreground notification:

const useFirebaseMessaging = () => {
  useEffect(() => {
    const messaging = getMessaging(firebaseApp);

    if (!messaging) return;

    const unsubscribe = onMessage(messaging, payload => {
      console.log('Foreground message received:', payload);

      if (Notification.permission === 'granted') {
        new Notification(payload.notification?.title || 'New Notification', {
          body: payload.notification?.body,
          icon: payload.notification?.image,
        });
      }
    });

    return () => unsubscribe();
  }, []);
};

Thank you.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744257070a238365.html

最新回复(0)