PWA集成FCM推送通知问题:重复通知与前台点击失效
PWA集成FCM推送通知问题解决方案
问题1:后台场景重复通知,禁用默认通知
原因
当FCM推送的Payload包含notification字段时,FCM SDK会自动触发默认通知;同时你在onBackgroundMessage中又手动调用showNotification,导致两条重复通知出现。
解决步骤
- 调整推送Payload结构:只传递
data字段,移除notification字段。示例Payload如下:
{ "data": { "title": "自定义标题", "body": "自定义内容", "icon": "/icon.png", "tag": "notification-tag", "link": "https://your-target-url.com" }, "token": "用户设备令牌" }
- 修改Service Worker逻辑:从
payload.data中读取通知参数,替代原有的payload.notification:
messaging.onBackgroundMessage((payload) => { const { title, body, icon, tag, link } = payload.data; self.registration.showNotification(title, { body: body, tag: tag, icon: icon, data: { url: link }, }); });
这样FCM不会自动弹出默认通知,完全由自定义逻辑处理通知展示。
问题2:前台场景通知点击无响应
原因
前台通过onMessage调用registration.showNotification()时,若未正确传递data参数,或Service Worker的notificationclick事件无法正确识别通知数据,会导致点击无响应。
解决步骤
- 前台
onMessage中传递完整data参数:
在页面的JS代码中调用showNotification时,确保把目标URL放入data字段:
messaging.onMessage((payload) => { const { title, body, icon, tag, link } = payload.data; registration.showNotification(title, { body: body, tag: tag, icon: icon, data: { url: link }, }); });
- 优化Service Worker的
notificationclick事件:增加参数校验,避免因数据缺失报错:
self.addEventListener('notificationclick', function (event) { console.log('On notification click: ', event); event.notification.close(); // 确保数据存在再执行跳转 if (event.notification.data?.url) { event.waitUntil( self.clients.openWindow(event.notification.data.url) ); } });
- 验证Service Worker状态:在浏览器开发者工具的
Application > Service Workers中,确认Service Worker处于激活状态,若存在旧缓存版本,需刷新并重新注册。
内容的提问来源于stack exchange,提问作者phong vu
相关产品推荐
相关产品推荐

