Nuxt集成Firebase时FCM推送通知重复到达问题求助
重复通知根因
当前出现后台双通知的核心是触发了两套通知展示逻辑:
- Firebase Messaging 内置的服务Worker逻辑会自动识别携带
notification字段的推送 payload,默认弹出系统通知 - 你自定义的全局
push事件监听额外手动调用了showNotification方法,二次弹出通知
修复方案
现有Nuxt配置无需调整,配置参考如下
services: { auth: true, // 示例配置,可替换为任意其他服务 messaging: { createServiceWorker: true, fcmPublicVapidKey: "###", // 可选:初始化后为FCM设置vapid密钥 inject: fs.readFileSync("./serviceWorker.js") } }
调整Service Worker代码
删除原有无效的setBackgroundMessageHandler逻辑,同时在push事件中阻止事件冒泡,避免Firebase默认逻辑二次处理:
self.addEventListener("push", function(e) { // 阻止事件继续传播,屏蔽Firebase默认通知处理逻辑 e.stopImmediatePropagation(); const data = e.data.json(); const options = { tag: "notification-1", body: data.notification.body, vibrate: [100, 50, 100], data: { dateOfArrival: Date.now(), primaryKey: "1" } }; self.registration.showNotification(data.notification.title, options); }); self.addEventListener( "notificationclick", function(event) { console.log("test", event); event.notification.close(); const url = "home"; event.waitUntil( self.clients.matchAll({ type: "window" }).then(windowClients => { // 检查是否已打开对应地址的标签页 for (let i = 0; i < windowClients.length; i++) { const client = windowClients[i]; // 存在对应标签页则直接聚焦 if (client.url === url && "focus" in client) { return client.focus(); } } if (self.clients.openWindow) { console.log("open window"); } }) ); }, false );
备选优化方案
如果不想修改事件监听逻辑,也可以调整后端推送的payload结构,去掉notification字段,所有内容都放在data字段中传递,Firebase默认逻辑就不会自动触发通知,也能解决重复问题。
内容的提问来源于stack exchange,提问作者mr_robot
相关产品推荐
相关产品推荐

