javascript Firebase消息传递onMessage仅在窗口中可用

vsmadaxz  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(53)

我在我的项目中实现了Firebase Cloud Messaging来发送和接收推送通知。我可以接收推送通知,但我无法让通知事件工作。具体来说,我想让onMessage事件工作,但由于某种原因,它给了我这个错误:
消息传递:此方法在Window上下文中可用。(消息传递/only-available-in-window)。
这是我的消息传递服务工作者:

// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here, other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-messaging.js')

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
  messagingSenderId: 'XXXXXXXX'
})

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging()
// messaging.setBackgroundMessageHandler(payload => {
//   console.log(payload)
// })
messaging.onMessage(function(payload) {
  // Messages received. Either because the
  // app is running in the foreground, or
  // because the notification was clicked.
  // `payload` will contain your data.
  console.log('Message received. ', payload)
})

字符串
我也试着把这个函数添加到我的Vue组件中,但是我仍然得到同样的错误。我做错了什么?

6ojccjat

6ojccjat1#

onMessage回调不应该在service worker中注册。在service worker中,您应该使用(请参阅Firebase文档):

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // ...
});

字符串
我可以确认这个功能目前对我有效。请注意,只有当您的应用处于后台,并且您正在发送数据消息时才会触发此功能。如果您正在发送 * 通知 *,则SDK会自动处理消息的显示,不会触发您的setBackgroundMessageHandler回调。即使您发送的payload同时包含 datanotification 内容,SDK会介入。
如果你想对service worker之外的消息做出React,请注意,包含你的网站的标签应该在前台。然后下面的代码应该可以工作(和你之前的一样):

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


我在我的Vue组件中有上面的代码片段(尽管我使用的是Vue 3),我没有得到错误,但是回调也没有被触发。也许你会有更好的运气。这应该对任何类型的消息触发,无论是 datanotification,还是两者兼而有之。
还要注意链接文档顶部的表格,以了解何时会触发回调。

编辑:显然,当您通过npm/Yarn安装的Firebase JS SDK与您从service worker导入的版本不相同时,不会触发onMessage回调。例如,我从npm导入的版本是7.2.3,而service worker导入的版本是6.3.4。将service worker更新为7.2.3后,onMessage回调在应用程序处于前台时被触发。感谢ErAz 7!

相关问题