React Js Firebase Cloud 消息传递在屏幕处于活动状态时未收到通知

React Js Firebase Cloud messaging not recieving notifications when screen is active

这是我的索引文件

import * as firebase from "firebase";

firebaseConfig = {
     apiKey: "x",
     authDomain: "x",
     databaseURL: "x",
     projectId: "x",
     storageBucket: "x",
     messagingSenderId: "x",
     appId: "x"
};

firebase.initializeApp(firebaseConfig);

const messaging = firebase.messaging();

Notification.requestPermission().then((permission) => {
  if (permission === 'granted') {
    console.log('Notification permission granted.');
    return messaging.getToken().then(function (token)
    {
        console.log(token, 'firebase token generated here');
        localStorage.setItem('fcmToken', token);
    })
  } else {
    console.log('Unable to get permission to notify.');
  }
});

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

const googleAuthProvider = new firebase.auth.GoogleAuthProvider();

export { firebase, googleAuthProvider };

这是我的 firebase-messaging-sw.js 文件

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

firebase.initializeApp({
    messagingSenderId: "x",
});

const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {

     console.log(payload);
     console.log('[firebase-messaging-sw.js] Received background message ', payload);
     // Customize notification here
      const notificationTitle = payload.data.title;
      const notificationOptions = {
        body: payload.data.body,
        icon: '/xxx.png'
      };

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

我正在尝试发送来自邮递员的通知。 当标签不活动时。出现通知。甚至 firebase-messaging-sw.js 也捕获了 console.log 但当标签处于活动状态时

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

这不会在 index.js

中触发

这是我要发送的负载。

{
 "to" : "x",
 "notification" : {
 "body" : "great match!!!!!!!!",
 "title" : "Portugal vs. Denmark!!!!!!!!!!!!!!!!1",
 "content_available" : true,
 "priority" : "high",
 },
 "data" : {
 "body" : "great match..............",
 "title" : "Portugal vs. Denmark..............",
 "content_available" : true,
 "priority" : "high",
 }
}

我什至尝试了不同组合的负载

{
 "to" : "x",
 "notification" : {
 "body" : "great match!!!!!!!!",
 "title" : "Portugal vs. Denmark!!!!!!!!!!!!!!!!1",
 "content_available" : true,
 "priority" : "high",
 },
}

也喜欢

{
 "to" : "x",
 "data" : {
 "body" : "great match..............",
 "title" : "Portugal vs. Denmark..............",
 "content_available" : true,
 "priority" : "high",
 }
}

好的,所以终于找到了答案。 我认为这不是直接解决方法,而是一种解决方法。

navigator.serviceWorker.addEventListener("message", (message) => {
    console.log(message);
});