reactjs 使用react失去焦点firebase时,未在messaging.onMessage事件中接收消息

ycggw6v2  于 2023-02-15  发布在  React
关注(0)|答案(1)|浏览(142)

当我失去焦点时,我没有在messaging.onMessage事件中收到消息,但我在公共文件夹中包含的SW文件中收到了messaging.onBackgroundMessage事件中的消息。这里的问题是如何将数据从SW文件传递到通知文件以显示它
软件文件:

const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  const notificationTitle = 'new notification';
  const notificationOptions = {
    body: '',
    icon: '',
  };
  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});

通知文件:

messaging?.onMessage((payload) => {
        console.log(payload, 'payload');
      });
o7jaxewo

o7jaxewo1#

我遇到了同样的问题,我通过将消息从onBackgroundMessage传递到客户端并在客户端代码中侦听来自服务工作者的消息来修复它
下面是我所做:

messaging.onBackgroundMessage(messaging, payload => {
  self.clients
    .matchAll({
      type: 'window',
      includeUncontrolled: true,
    })
    .then(all =>
      all.forEach(client => {
        client.postMessage(payload);
      })
    );
    ...

在客户端代码中:

navigator.serviceWorker.addEventListener('message', function handler(event) {
        console.log(event)
      });

相关问题