You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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);
  }
});

补充说明

  1. 你之前的尝试无效,是因为问题根源不在FCM的推送逻辑,而是Service Worker的系统更新提示。
  2. 若需要告知用户应用更新,可通过postMessage向前台页面发送消息,在页面内展示自定义更新提示,替代浏览器默认通知。
  3. 测试时可通过Chrome DevTools的Application -> Service Workers面板,勾选"Update on reload"模拟Service Worker更新,验证修改效果。

内容的提问来源于stack exchange,提问作者user9083933

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 14:45:39