Firebase notification onMessage not hitting when c

2019-07-13 18:52发布

问题:

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.

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.

回答1:

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 :)



回答2:

When your website is not in the active tab, Firebase SDK will either show a notification or call the function that you can set using setBackgroundMessageHandler. If your payload includes a notification field, a notification will be shown. Otherwise, your callback will be called.

I recommend that you don't send a notification payload (you can still send it inside the data field, and write a background message handler.

See this Firebase guide for more information.