首页 > 解决方案 > Firebase 网络推送通知发送成功但客户端未收到

问题描述

我正在使用 Firebase Web 推送通知 API 并发送带有我想在客户端使用 Postman 和/或从 Firebase 通知编写器显示的消息的帖子请求,消息已成功发送但未收到,如何我可以解决这个问题吗?

这是我得到的回应

{
    "multicast_id": 6360733777037549929,
    "success": 1,
    "failure": 0,
    "canonical_ids": 0,
    "results": [
        {
            "message_id": "0:1592759038463623%cc9b4facf9fd7ecd"
        }
    ]
}

我正在使用 Firebase 托管,并包含整个 Firebase Javascript SDK,尽管我已经尝试过仅包含 firebase-messaging SDK。

  <body>
    <h1>Some Firebase app</h1>
    <script src="/__/firebase/7.15.3/firebase.js"></script>
    <script src="/__/firebase/init.js"></script>
    <script type="text/javascript">
      const messaging = firebase.messaging();
      messaging.requestPermission()
      .then(()=>{
        console.log('Permission Granted');
        return messaging.getToken()
      })
      .then((token)=>{
        console.log(token);
      })
      .catch((err)=>{
        console.log(err);
      })
      
      messaging.onMessage((payload) => {
        console.log('Message received. ', payload);
      });

    </script>
  </body>

使用我得到的令牌,并使用我的服务器密钥,我发送以下请求

Method: POST
URL: https://fcm.googleapis.com/fcm/send
Headers: {
  Authorization: "key=myServerKey",
  Content-Type: "application/json"
  }
Body: {
  "to" : "token",
  "notification" : {
            "body" : "Test message",
            "title" : "Test title"
           }
  }

这就是我在 firebase-messaging-sw.js 文件中处理消息的方式

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

var firebaseConfig = {
  apiKey: "xxxx",
  authDomain: "newproject-95acc.firebaseapp.com",
  databaseURL: "https://newproject-95acc.firebaseio.com",
  projectId: "newproject-95acc",
  storageBucket: "newproject-95acc.appspot.com",
  messagingSenderId: "xxxx",
  appId: "xxxx"
};

firebase.initializeApp(firebaseConfig);

messaging.onMessage((payload) => {
  console.log('Message received. ', payload);
});

标签: javascriptfirebasepush-notificationfirebase-cloud-messagingweb-push

解决方案


您想在前台(有焦点)还是在后台(服务人员)接收消息?

在后台(服务人员)

你能试试下面的代码吗?

firebase-messaging-sw.js

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

var firebaseConfig = {
  apiKey: "xxxx",
  authDomain: "newproject-95acc.firebaseapp.com",
  databaseURL: "https://newproject-95acc.firebaseio.com",
  projectId: "newproject-95acc",
  storageBucket: "newproject-95acc.appspot.com",
  messagingSenderId: "xxxx",
  appId: "xxxx"
};

firebase.initializeApp(firebaseConfig);

if (firebase.messaging.isSupported()) {
  firebase.messaging();
}

请参阅https://firebase.google.com/docs/cloud-messaging/js/receive

如果您在消息负载中设置通知字段,则不会调用您的 setBackgroundMessageHandler 回调,而是 SDK 会根据您的负载显示通知。

或者,你能试试样品吗?

看:


推荐阅读