【问题标题】:Firebase messaging onMessage only available in a windowFirebase 消息传递 onMessage 仅在窗口中可用
【发布时间】:2020-01-13 00:48:05
【问题描述】:

我在我的项目中实现了 Firebase 云消息传递来发送和接收推送通知。我可以接收推送通知,但我无法让通知事件正常工作。具体来说,我想让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)
})

我也尝试将函数添加到我的 Vue 组件,但我仍然得到同样的错误。我做错了什么?

【问题讨论】:

    标签: javascript firebase vue.js vuejs2 firebase-cloud-messaging


    【解决方案1】:

    onMessage 回调不应在服务工作者中注册。在你应该使用的服务工作者中(见Firebase docs):

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

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

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

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

    我的 Vue 组件中有上述 sn-p(虽然我使用的是 Vue 3),但我没有收到错误,但回调也没有被触发。也许你会有更好的运气。这应该针对任何类型的消息触发,无论是 datanotification 还是两者兼有。

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

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

    【讨论】:

    • 你救了我半条命。在面对这个问题超过 12 小时后,我恢复了生活。我面临的是版本问题,它真的很糟糕
    • 你在哪里使用下面的调用? ```messaging.onMessage((payload) => { console.log('Message received.', payload); // ... }); ```我试图在创建的钩子中调用它,但它说消息未定义。
    猜你喜欢
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 2021-06-16
    • 2020-01-21
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 2017-04-05
    相关资源
    最近更新 更多