使用Firebase Cloud Messaging接收消息正常但Chrome无通知弹窗如何解决
核心问题定位
从你贴的控制台输出可以直接定位根因:你收到的是Firebase数据类型消息,通知配置被序列化为字符串存在payload.data.notification字段下,现有代码直接读取payload.notification会得到undefined,自然无法渲染通知。
需要修正的配置项
1. 修正前台消息接收逻辑
替换你index文件里的onMessage代码,先解析数据字段里的通知配置,同时简化Service Worker获取逻辑避免自定义scope不匹配:
messaging.onMessage((payload) => { console.log('Message received. ', payload); // 解析data字段里的通知配置 const notification = JSON.parse(payload.data.notification); // 直接用ready获取已激活的Service Worker注册,不用硬写scope navigator.serviceWorker.ready.then(registration => { registration.showNotification( notification.title, { body: notification.body, icon: notification.icon, data: { click_action: notification.click_action } } ) }); });
2. 修正后台消息接收逻辑
替换firebase-messaging-sw.js里的setBackgroundMessageHandler代码,同样从data字段解析通知配置:
messaging.setBackgroundMessageHandler(function (payload) { console.log('[firebase-messaging-sw.js] Received background message ', payload); // 解析数据里的通知配置 const notification = JSON.parse(payload.data.notification); const notificationTitle = notification.title; const notificationOptions = { body: notification.body, icon: notification.icon, image: notification.image, data: { click_action: notification.click_action } }; return self.registration.showNotification( notificationTitle, notificationOptions ); });
3. 补充必要的辅助配置
通知点击跳转(可选但建议补充)
在firebase-messaging-sw.js里添加点击事件监听,实现点击通知跳转对应页面:
self.addEventListener('notificationclick', function(event) { event.notification.close(); if (event.notification.data.click_action) { event.waitUntil( clients.openWindow(event.notification.data.click_action) ); } });
手动注册Service Worker(避免路径不匹配)
在index文件的firebase初始化完成后,添加手动注册代码,覆盖默认自动注册逻辑:
if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/firebase-messaging-sw.js') .then(registration => { console.log('SW registered: ', registration); // 将注册的Service Worker绑定到messaging实例 messaging.useServiceWorker(registration); }) .catch(err => { console.log('SW registration failed: ', err); }); }); }
4. 检查环境权限配置
- 点击浏览器地址栏左侧锁图标,进入站点设置,确认通知权限已设置为「允许」
- 确认操作系统的通知设置没有禁用Chrome的通知权限
- 测试请使用普通Chrome窗口,隐身模式默认禁用Service Worker无法弹出通知
- 生产环境必须使用HTTPS协议,Service Worker仅支持HTTPS和localhost开发环境
补充说明:如果从Firebase控制台发送的是「通知类型消息」而非自定义数据消息,Firebase会自动处理通知弹出,不需要手动解析字段写渲染逻辑,只有自定义数据消息需要手动处理
payload.data里的内容。
内容的提问来源于stack exchange,提问作者UpaJah
相关产品推荐
相关产品推荐

