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

Firebase Cloud Messaging中onMessage前台事件不触发问题求助

Firebase Cloud Messaging中onMessage前台事件不触发问题求助

我遇到了FCM的一个棘手问题,想请大家帮忙排查下:当网站处于后台(未聚焦)状态时,onBackgroundMessage能正常接收通知并执行逻辑,但前台聚焦状态下onMessage完全没反应——甚至连控制台日志都打不出来。两个函数里的代码逻辑完全一致,实在搞不懂哪里出问题了!

客户端Token注册/刷新代码

if (Notification.permission === 'granted') {
   getToken(messaging, { vapidKey: process.env.PUBLIC_FIREBASE_FCM_VAPID_KEY }).then((currentToken) => {
      if (currentToken) {
         <STORE KEY IN DATABASE>
      }
   }).catch((err) => {
      console.log('An error occurred while retrieving token. ', err);
   });
} else {
   <REMOVE ANY KEYS STORED IN DATABASE>
}

服务端消息推送代码

const admin = require('firebase-admin');
const message1 = {
   token: '<TOKEN>',
   data: {
      title: 'Test',
      body: 'Test',
   },
   webpush: {
      fcmOptions: {
         link: '/',
      }
   }
};
const messages = [message1];

try {
   const result = await admin.messaging().sendEach(messages);
   console.log(result?.responses);
} catch (error) {
   console.log(error);
}

服务Worker代码

importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.13.2/firebase-messaging-compat.js');

const firebaseApp = firebase.initializeApp({
    apiKey: "<API KEY>",
    authDomain: "<DOMAIN>",
    projectId: "<PROJECT_ID>",
    storageBucket: "<STORAGE_BUCKET>",
    messagingSenderId: "<SENDER_ID>",
    appId: "<APP_ID>",
    measurementId: "<MEASUREMENT_ID>"
});

const messaging = firebase.messaging();

messaging.onMessage((payload) => {
    console.log('Foreground Message recieved', payload);

    if (payload.data.type === 'clear') {
        self.registration.getNotifications()
            .then(notifications => {
                notifications.forEach(notification => notification.close());
            });
    } else {
        const notificationTitle = payload.data.title;
        const notificationOptions = {
            body: payload.data.body,
            tag: '<TAG>',
            renotify: true,
            icon: '/images/icons-192.png',
            data: {
                url: "/"
            }
        }
        self.registration.showNotification(notificationTitle, notificationOptions);
    }
});

messaging.onBackgroundMessage((payload) => {
    console.log('Background Message recieved', payload);

    if (payload.data.type === 'clear') {
        self.registration.getNotifications()
            .then(notifications => {
                notifications.forEach(notification => notification.close());
            });
    } else {
        const notificationTitle = payload.data.title;
        const notificationOptions = {
            body: payload.data.body,
            tag: '<TAG>',
            renotify: true,
            icon: '/images/icons-192.png',
            data: {
                url: "/"
            }
        }
        self.registration.showNotification(notificationTitle, notificationOptions);
    }
});

self.addEventListener('notificationclick', function (event) {
    event.notification.close();

    event.waitUntil(
        clients.matchAll({
            type: "window"
        })
            .then(function (clientList) {
                for (var i = 0; i < clientList.length; i++) {
                    var client = clientList[i];
                    if (client.url == '/' && 'focus' in client)
                        return client.focus();
                }
                if (clients.openWindow) {
                    return clients.openWindow('/');
                }
            })
    );
});

目前的具体现象:

  • 网站未聚焦时,onBackgroundMessage能正常接收消息并触发对应逻辑
  • 网站聚焦时,onMessage完全没有触发,控制台也看不到对应的日志输出

两个函数的代码逻辑完全一致,实在找不到问题所在,有没有朋友能帮我梳理下可能的原因?

备注:内容来源于stack exchange,提问作者Alexander Mason

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 19:49:27