PWA站点已打开聚焦时如何处理Firebase推送通知
解决方案
1. 调整FCM推送消息结构
你当前只发送了notification类型的FCM消息,这类消息的默认逻辑是:仅当应用处于后台/未打开状态时,才会由FCM SDK自动触发系统通知,前台运行时会被直接丢弃不会传递到应用层。
要实现全场景接收,需要改为发送混合类型消息,把业务参数同时放到data字段中,示例修改后的发送代码:
function sendNotification(){ const toSend ={ // 保留notification字段,保证后台/未打开场景下FCM自动弹通知 notification: { title:"Video Call!", body:"Video call!", click_action: "https://....netlify.app/?x="+m, sound: "default", vibrate: [200, 100, 200, 100, 200, 100, 200] }, // 新增data字段,存放业务参数,前台场景下会传递到你的业务回调 data: { type: "video_call", callId: m, title:"Video Call!", body:"Video call!", click_action: "https://....netlify.app/?x="+m }, to:othermailandtoken[1] }; const jsonString = JSON.stringify(toSend); var xhr = new XMLHttpRequest(); xhr.open('POST', 'https://fcm.googleapis.com/fcm/send', true); xhr.onload = function(){ console.log("google response: ",this.responseText); } xhr.setRequestHeader("Content-type", "application/json"); xhr.setRequestHeader("Authorization","key=...."); xhr.send(jsonString); }
2. 前台页面添加推送监听
在你的PWA前台页面代码中,添加FCM的onMessage事件监听,应用处于前台运行时,推送消息会触发这个回调,你可以在这里做差异化处理,比如弹页面内的呼叫弹窗、播放呼叫铃声等:
// 确保已经初始化了FCM SDK实例 import { getMessaging, onMessage } from "firebase/messaging"; const messaging = getMessaging(); onMessage(messaging, (payload) => { console.log('前台收到推送消息', payload); const data = payload.data; // 自定义前台场景的处理逻辑 if(data.type === 'video_call') { // 示例1:弹页内呼叫提示 showCallModal(data.callId); // 示例2:也可以主动调用系统通知API弹通知 if(Notification.permission === 'granted') { new Notification(data.title, { body: data.body, icon: '/icon.png', vibrate: [200, 100, 200] }); } } });
3. Service Worker兼容处理(可选)
如果需要完全自主控制所有场景的通知展示,也可以改为只发送data类型的消息(去掉payload中的notification字段),然后在Service Worker中添加onBackgroundMessage监听,处理后台场景的通知弹出:
// service-worker.js 中添加 import { getMessaging, onBackgroundMessage } from "firebase/messaging/sw"; const messaging = getMessaging(); onBackgroundMessage(messaging, (payload) => { console.log('后台收到推送消息', payload); const data = payload.data; self.registration.showNotification(data.title, { body: data.body, icon: '/icon.png', data: { url: data.click_action } }); }); // 监听通知点击事件 self.addEventListener('notificationclick', (event) => { event.notification.close(); event.waitUntil( clients.openWindow(event.notification.data.url) ); });
内容的提问来源于stack exchange,提问作者SlimLamie
相关产品推荐
相关产品推荐

