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

Tar*_*epp 2 javascript firebase vue.js firebase-cloud-messaging vuejs2

我在我的项目中实现了 Firebase Cloud Messaging 来发送和接收推送通知。我可以接收推送通知,但我无法使通知事件起作用。具体来说,我想让onMessage事件工作,但由于某种原因,它给了我这个错误:

消息传递:此方法在 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)
})
Run Code Online (Sandbox Code Playgroud)

我也尝试将该函数添加到我的 Vue 组件中,但我仍然遇到相同的错误。我究竟做错了什么?

Dua*_*mse 6

onMessage回调不应该从服务工作者中注册。在您应该使用的服务工作者中(请参阅Firebase 文档):

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

我可以确认这目前对我有用。请注意,这只会在您的应用程序处于后台并且您正在发送数据消息时触发。如果您正在发送通知,则 SDK 将自动处理消息的显示,并且setBackgroundMessageHandler不会触发您的回调。即使您发送包含数据通知内容的有效负载,SDK 也会进行干预。

如果您想对 Service Worker 之外的消息做出反应,请注意包含您网站的选项卡应位于前台。然后下面的代码应该可以工作(和你之前的一样):

messaging.onMessage((payload) => {
  console.log('Message received. ', payload);
  // ...
});
Run Code Online (Sandbox Code Playgroud)

我的 Vue 组件中有上面的代码片段(尽管我使用的是 Vue 3),我没有收到错误消息,但也没有触发回调。也许你会有更好的运气。这应该针对任何类型的消息触发,无论是datanotification还是两者。

另请注意链接文档顶部的表格,以了解何时触发哪个回调。

编辑:显然,onMessage当您通过 npm/Yarn 安装的 Firebase JS SDK 与您从 Service Worker 导入的版本不同时,不会触发回调。例如,我的 npm 版本是 7.2.3,Service Worker 导入的版本是 6.3.4。使用 7.2.3 更新 Service Worker 后,onMessage当应用程序处于前台时会触发回调。感谢 ErAz7