Firebase设置后台消息处理程序 [英] firebase set background message handler

查看:89
本文介绍了Firebase设置后台消息处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在前端自定义通知消息,即,如果未设置发送通知字段,我将尝试添加它.

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

在执行上面的代码时,即使收到通知,我也没有获得[firebase-messaging-sw.js] Received background message ', payload的控制台.

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.

为什么setBackgroundMessageHandler不起作用?

推荐答案

在应用程序在后台运行时,您发出了发送消息的json请求中的问题.

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

注意:如果您在HTTP或XMPP发送请求中设置了通知字段,则这些值将优先于服务工作者中指定的任何值.

https://firebase.google.com/docs/cloud- messages/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"
    }
  }
}

这篇关于Firebase设置后台消息处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆