firebase set background message handler

血红的双手。 提交于 2020-01-05 13:30:12

问题


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"
    }
  }
}


来源:https://stackoverflow.com/questions/50755931/firebase-set-background-message-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!