获取fcm的setBackgroundMessageHandler函数内的文档

问题描述 投票:0回答:1

下面是我的fcm setBackgroundMessageHandler功能:

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };
var event = new CustomEvent("name-of-event", payload);

// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);
  return self.registration.showNotification(notificationTitle,
      notificationOptions);
});

我无法通过上述方法访问document。我试图在全局变量中保存文档并在上面的方法中访问它但它不起作用。

var document = document;
.
.
.
document.dispatchEvent(event); // gives error: dispatchEvent of undefined
javascript firebase firebase-cloud-messaging
1个回答
1
投票

由于服务工作者无法访问document。所以没有办法使用它的dispatchEvent函数向主页面发出事件。

要从服务工作者发送消息到Main page,我们可以使用BroadcastChannel。在Main页面中创建一个这样的监听器:

var listener = new BroadcastChannel('listener');
listener.onmessage = function(e) {
  console.log('Got message from service worker',e);
};

service worker js文件中使用BroadcastChannelpostMessage函数向主页发送消息:

var listener = new BroadcastChannel('listener');
listener.postMessage('It works !!');
© www.soinside.com 2019 - 2024. All rights reserved.