Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase notification onMessage not hitting when chrome tab is open but not active

I have setup firebase messaging service and it works like a charm. Only problem is in messaging.onMessage function I have incremented count of notification on my page. Additionally I also have service worker setup that throws chrome notifications in background.

notification bell with counter

When my tab is open but not active, messaging.onMessage is not getting hit, but background handler service worker is hitting. So counter on my website is not increasing. When user goes to my website tab back again, it shows old notification count. That is creating bad UX. I am showing notifications list on click of count as like facebook shows.

like image 718
Savan S Avatar asked May 05 '18 11:05

Savan S


People also ask

How do I get Firebase to push notifications?

Go to Firebase console — →Project Settings — →Cloud Messaging. To send the message select Body — →Raw — →JSON(application/json). You can send Notification Payload , Data Payload and even both using POSTMAN service.

How does Firebase push notification work internally?

The FCMFCMFirebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost.https://firebase.google.com › docs › cloud-messagingFirebase Cloud Messaging backend receives the message request, generates a message ID and other metadata, and sends it to the platform specific transport layer. When the device is online, the message is sent via the platform-specific transport layer to the device. On the device, the client app receives the message or notification.

Is there a limit for Firebase notifications?

Notification messages can contain an optional data payload. Maximum payload for both message types is 4000 bytes, except when sending messages from the Firebase console, which enforces a 1024 character limit. FCMFCMFirebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost.https://firebase.google.com › docs › cloud-messagingFirebase Cloud Messaging automatically displays the message to end-user devices on behalf of the client app.


1 Answers

I'm not sure how you're updating the notification badge count. But, you could retrieve the whole payload in the callback function below:

for background:

messaging.setBackgroundMessageHandler(function(payload) {

     console.log(payload.data.badgeCount);

     return self.registration.showNotification(title, options);
});

for foreground:

messaging.onMessage(function(payload) {

     console.log(payload.data.badgeCount);

});

Whether the web app is in foreground or background state, get the payload in the onMessage callback and setBackgroundMessageHandler callback, respectively, then update the UI.

Hope this helps :)

like image 133
looptheloop88 Avatar answered Sep 24 '22 02:09

looptheloop88