React应用FCM后台推送出现重复通知问题求助
解决React+FCM后台推送时出现额外通知的问题
问题根源
你遇到的那条"This site has been updated in background"通知,是Chrome/Edge浏览器检测到Service Worker更新时的默认系统提示。当应用标签页处于后台但未关闭时,浏览器会自动检查Service Worker的更新状态,一旦发现新版本就弹出这条通知,刚好和你通过FCMonBackgroundMessage触发的通知同时出现,造成"额外通知"的现象。
解决方案
在你的firebase-messaging-sw.js中添加Service Worker更新事件的处理逻辑,阻止浏览器的默认通知,手动控制更新流程。具体修改如下:
//firebase-messaging-sw.js // Scripts for firebase and firebase messaging importScripts('https://www.gstatic.com/firebasejs/9.6.1/firebase-app-compat.js'); importScripts('https://www.gstatic.com/firebasejs/9.6.1/firebase-messaging-compat.js'); const firebaseConfig = { apiKey: '', authDomain: '', projectId: '', storageBucket: '', messagingSenderId: '', appId: '', measurementId: '' }; firebase.initializeApp(firebaseConfig); const messaging = firebase.messaging(); // 新增:处理Service Worker更新,阻止默认通知 self.addEventListener('updatefound', () => { const newWorker = self.registration.installing; newWorker.addEventListener('statechange', () => { // 当新Service Worker激活时,跳过浏览器默认通知 if (newWorker.state === 'activated') { // 可选:通过postMessage通知前台页面自定义更新提示 // self.clients.matchAll({ type: 'window' }).then(clients => { // clients.forEach(client => { // client.postMessage({ type: 'SW_UPDATED' }); // }); // }); } }); }); // 可选:阻止页面自动刷新(若不需要自动更新页面) self.addEventListener('controllerchange', () => {}); messaging.onBackgroundMessage(function (payload) { if (payload ) { const notificationTitle = payload.data.title; const notificationOptions = { body: payload.data.body, data: payload.data.clickEvent }; return self.registration.showNotification(notificationTitle, notificationOptions); } });
补充说明
- 你之前的尝试无效,是因为问题根源不在FCM的推送逻辑,而是Service Worker的系统更新提示。
- 若需要告知用户应用更新,可通过
postMessage向前台页面发送消息,在页面内展示自定义更新提示,替代浏览器默认通知。 - 测试时可通过Chrome DevTools的
Application -> Service Workers面板,勾选"Update on reload"模拟Service Worker更新,验证修改效果。
内容的提问来源于stack exchange,提问作者user9083933
相关产品推荐
相关产品推荐

