Javascript Firebase消息onMessage仅在窗口中可用
我在我的项目中实现了Firebase云消息传递,以发送和接收推送通知。我可以接收推送通知,但无法使通知事件正常工作。具体地说,我想让Javascript Firebase消息onMessage仅在窗口中可用,javascript,firebase,vue.js,vuejs2,firebase-cloud-messaging,Javascript,Firebase,Vue.js,Vuejs2,Firebase Cloud Messaging,我在我的项目中实现了Firebase云消息传递,以发送和接收推送通知。我可以接收推送通知,但无法使通知事件正常工作。具体地说,我想让onMessage事件正常工作,但由于某些原因,它给了我以下错误: 消息传递:此方法在窗口上下文中可用。 (消息/仅在窗口中可用) 这是我的邮件服务人员: // Give the service worker access to Firebase Messaging. // Note that you can only use Firebase Messaging
onMessage
事件正常工作,但由于某些原因,它给了我以下错误:
消息传递:此方法在窗口上下文中可用。
(消息/仅在窗口中可用)
这是我的邮件服务人员:
// 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组件中,但仍然出现相同的错误。我做错了什么?不应从服务人员内部注册
onMessage
回调。在服务人员中,您应该使用(请参阅):
我可以确认,这是目前为我工作。请注意,只有当您的应用程序处于后台且您正在发送数据消息时,才会触发此操作。如果您正在发送通知,则SDK将自动处理消息的显示,并且不会触发您的setBackgroundMessageHandler
回调。即使发送包含数据和通知内容的有效负载,SDK也会进行干预
如果您想对服务人员之外的消息做出反应,请注意,包含您的网站的选项卡应位于前台。然后,以下代码应该可以工作(与您的代码相同):
我的Vue组件中有上述代码段(尽管我使用的是Vue 3),我没有收到错误,但是也没有触发回调。也许你会有更好的运气。对于任何类型的消息,无论是数据、通知还是两者,都应触发此操作
还要注意链接文档顶部的表格,以了解何时将触发哪个回调
编辑:当您通过npm/Thread安装的Firebase JS SDK与您从服务人员导入的版本不同时,显然不会触发
onMessage
回调。例如,npm的版本是7.2.3,服务人员导入的版本是6.3.4。使用7.2.3更新service worker后,当应用程序位于前台时,onMessage
回调被触发 你救了我一半的命。在面对这个问题12个多小时后,我重新找回了我的生活。我所面临的是版本问题,它真的很糟糕。你在用下面的电话吗messaging.onMessage((有效负载)=>{console.log('Message received',payload);/…});`我试图在创建的钩子中调用它,但它说消息传递是未定义的。
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// ...
});
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// ...
});