I received 2 notifications in background case and can not handle click in foreground case
I am implementing push notification function on PWA using FCM. But I am getting issues
- In background case. On firebase-messaging-sw.js file. I implemented
self.addEventListener('notificationclick', function (event) {}
I received 2 notifications. But this event only runs when I click notification is clicked by onBackgroundMessage
messaging.onBackgroundMessage((payload) => {
const { title, body, icon, tag } = payload.notification;
self.registration.showNotification(title, {
body: body
tag: tag
icon: icon
data: { url: payload.data.link },
});
});
How to disable default background notification. I want to only show notification 1 time handled by onBackgroundMessage
- On foreground case. I call registration.showNotification() to show notification in onMessage event to display notification. How to handle the click event in this case? notificationclick in firebase-messaging-sw.js seem is not work.
This is my sw file:
importScripts(
'https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js'
);
importScripts(
'https://www.gstatic.com/firebasejs/10.7.0/firebase-messaging-compat.js'
);
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
const { title, body, icon, tag } = payload.notification;
self.registration.showNotification(title, {
body: body,
tag: tag,
icon: icon,
data: { url: payload.data.link },
});
});
self.addEventListener('push', function (event) {
console.log('Received a push message', event);
});
self.addEventListener('notificationclick', function (event) {
console.log('On notification click: ', event);
let data = event.notification.data;
event.notification.close();
self.clients.openWindow(data.url);
});