I am using FCM to handle push notifications, but notification is coming in data
key instead of notification
.
Here is the code I am using to handle new message and show as notification.
I am seeing notification with all options and data as I specified. However, when I click notification, it doesn't fire any "notificationclick" event. It also doesn't print event.notification
.
importScripts('https://www.gstatic.com/firebasejs/5.3.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.3.1/firebase-messaging.js');
firebase.initializeApp({
messagingSenderId: "SOME_ID",
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(payload => {
console.log(payload);
const options = {
body: payload.data.body,
icon: payload.data.icon,
click_action: payload.data.click_action,
link: payload.data.link,
data: {
time: new Date(Date.now()).toString(),
click_action: payload.data.click_action,
},
};
self.registration.showNotification(payload.data.title, options);
});
self.addEventListener("notificationclick", function(event) {
console.log(event.notification);
const clickedNotification = event.notification;
clickedNotification.close();
const urlToOpen = clickedNotification.data && clickedNotification.data.click_action;
const promiseChain = clients.matchAll({
type: 'window',
includeUncontrolled: true,
})
.then((windowClients) => {
let matchingClient = null;
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
if (windowClient.url === urlToOpen) {
matchingClient = windowClient;
break;
}
}
if (matchingClient) {
return matchingClient.focus();
} else {
return clients.openWindow(urlToOpen);
}
});
event.waitUntil(promiseChain);
});