firebase set background message handler

2019-08-05 19:30发布

问题:

I have been trying to customise notification message in front end, i.e if a field is not set send in notification, I am trying to add it.

importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-messaging.js');

var config = {
    apiKey: "x",
    authDomain: "y",
    databaseURL: "z",
    projectId: "a",
    storageBucket: "b",
    messagingSenderId: "1"
};

firebase.initializeApp(config);

const messaging = firebase.messaging();
console.log('came here');

console.log(messaging.bgMessageHandler);

console.log(messaging.setBackgroundMessageHandler,'dsafdsadasfd')




messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  var notificationTitle = 'Background Message Title';
  var notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

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

console.log(messaging.bgMessageHandler);

while executing the above code, I am not getting an console of [firebase-messaging-sw.js] Received background message ', payload, even though i am getting notification.

Why is the setBackgroundMessageHandler not working?

回答1:

It looks like problem within the json request that you made to send the message while app is running in background.

Note: If you set notification fields in your HTTP or XMPP send request, those values take precedence over any values specified in the service worker.

https://firebase.google.com/docs/cloud-messaging/js/topic-messaging

So,Following format won't call the background handler :

{
  to: "e-DLMv........._DiL",
  notification: {
    body: "Backgound-Message"
  }
}

Send message with notification inside data (It will work) :

{
  to: "e-DLMv........._DiL",
  data: {
    notification: {
      body: "Backgound-Message"
    }
  }
}