I am trying to send the push notification from the server usning fcm api. I have added all the service worker and code to request permision in flutter. Referred many documents and videos not able to solve it. I want to show the notification in background and foreground also. Please help me to resolve this. Thanks Below is my code of service worker, still it the notification is not arriving?
importScripts('https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.4.1/firebase-messaging.js');
/*Update with yours config*/
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
const promiseChain = clients
.matchAll({
type: "window",
includeUncontrolled: true
})
.then(windowClients => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
windowClient.postMessage(payload);
}
})
.then(() => {
const title = payload.notification.title;
const options = {
body: payload.notification.score
};
return registration.showNotification(title, options);
});
return promiseChain;
});
self.addEventListener('push', function(event) {
const options = {
body: event.data.text(),
icon: 'ic_stat_name', // Replace with the path to your notification icon
// Replace with the path to your notification badge
data: { url: '/' } // Replace with the URL you want to open when the notification is clicked
};
console.log('notification received: ', options)
event.waitUntil(
self.registration.showNotification('title', {
body: 'body'
})
);
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(
clients.openWindow(event.notification.data.url)
);
console.log('notification received: ', event)
});