Reputation: 1030
I have use fcm for push notification in my reactjs web application. I am able to get notification if the the web application is running in the background. But not able to get notification while my application is actively running in foreground.
Firebase initialization is perfectly done in my project,because I am successfully getting push notification in the background.
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': '337889493107'
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
const data = JSON.parse(payload.data.notification);
const notificationTitle = data.title;
const notificationOptions = {
body: data.body,
icon: '/favicon.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
messaging.onMessage(function(payload) {
const data = JSON.parse(payload.data.notification);
const notificationTitle = data.title;
const notificationOptions = {
body: data.body,
icon: '/favicon.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
Do I need to do any further modification to my foreground method messaging.onMessage
or do I need to do any more configuration. Plz help me out
Upvotes: 1
Views: 3304
Reputation: 3800
Please try to use Notifications API, instead of the Service Worker API.
messaging.onMessage(function(payload) {
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.icon,
};
if (!("Notification" in window)) {
console.log("This browser does not support system notifications.");
} else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification(notificationTitle,notificationOptions);
notification.onclick = function(event) {
event.preventDefault();
window.open(payload.notification.click_action , '_blank');
notification.close();
}
}
});
Upvotes: 6