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.