简体   繁体   中英

Firebase Cloud Messaging: Prevent background notifications in javascript client

I have a live score display website which is implemented with Google's channel API to push live score updates to the browser. Since Google is shutting down the channel API, I have to move to Firebase Cloud Messaging.

When I migrated to FCM, I had to add a service worker javascript file (firebase-messaging-sw.js). Whenever a score update is pushed to the browser, if the user is in another browser tab or the user has closed my web page tab, A notification appears to the user.

I don't need this notification and I want to disable it. Also, when user moves to another browser tab, I want to prevent the push message from going into the service worker and route it to my web page, so that when user returns to the tab again, the latest score is updated in the webpage.

Is there any way to achieve this?

You should pass a parameter (depends what you need to do) in the body of message like this:

$msg = [
  'title' => pushTitle,
  'body'=> pushBody,
  'icon'=> icon.png,
  'image'=> image.png,
  'active'=> 1
];

The above is PHP but is also working in the same way-idea in any programming language. If you use Firebase then you should use cloud functions.

then in your js file:

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('Received background message', payload);

  if(payload.data.active == 1){
    return;
  }
  var notificationTitle = payload.data.title;
  var notificationOptions = {
    body: payload.data.body,
    icon: payload.data.icon,
    image: payload.data.image
  };

  return self.registration.showNotification(notificationTitle, notificationOptions);
});

If I had your code(what did you have done until now) I would gave you an exact answer. If you have more questions don't hesitate to ask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM