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

FCM通知异常:Web端正常接收,React Native移动端无法接收

React Native移动端无法接收FCM数据消息,Web端正常的问题排查与解决

我使用FCM向Android、iOS及Web端推送通知,目前Web端可正常接收,但React Native移动端无法接收。后台日志显示通知已成功发送,但使用Firebase控制台的测试云消息功能时,情况相反:移动端可接收,Web端无法接收。

后端推送代码

const firebase = require("firebase-admin");
const { getMessaging } = require("firebase-admin/messaging");
const serviceAccountKey = require('./firebase-config.json')

const projectId = "PROJECT ID HERE"; // 已替换为真实项目ID

firebase.initializeApp({
  credential: firebase.credential.cert(serviceAccountKey),
  databaseURL: `https://${projectId}.firebaseio.com`
});


const sendNotification = async (user, tokens) => {
  const message = {
    data: {
      title: "Test Message",
      body: JSON.stringify({
        content: `this is a test message`,
        username: user.name,
        userId: user._id
      }),
    },
    tokens,
  };
  try {
    const res = await getMessaging().sendMulticast(message)
    console.log('successfully send message')
    console.log(res)
  } catch (error) {
    const code = error?.errorInfo?.code;
    console.log("Error sending message:", code);
    console.log("error", error);
    }
  };
}

Web端服务工作者代码(/firebase-messaging-sw.js)

self.addEventListener("push", (event) => {
  const data = event.data.json()?.data;
  const body = JSON.parse(data.body);
  console.log(url);
  const options = {
    body: body.content,
    icon: "/logo.png",
  };

  event.waitUntil(self.registration.showNotification(data.title, options));
});

问题根源

当前发送的是纯数据消息(data-only message),不同平台对这类消息的处理逻辑存在差异:

  • Web端:服务工作者(Service Worker)可直接监听push事件解析data字段,自行构建并显示通知,因此能正常接收。
  • React Native移动端:FCM SDK不会自动为纯数据消息触发系统通知,需客户端手动监听消息并构建通知。而Firebase控制台测试时发送的是通知消息(notification message),这类消息由FCM SDK自动在移动端弹出通知,所以控制台测试时移动端能收到。

解决方法

方法1:发送通知+数据的混合消息

修改后端消息结构,同时包含notification和data字段,既让移动端自动显示通知,又能携带自定义数据:

const message = {
  notification: {
    title: "Test Message",
    body: `this is a test message`
  },
  data: {
    username: user.name,
    userId: user._id
  },
  tokens,
};

适配效果:

  • 移动端:FCM SDK自动弹出系统通知,点击后可通过getInitialNotification或onNotificationOpenedApp获取data数据。
  • Web端:调整服务工作者逻辑,兼容混合消息格式:
self.addEventListener("push", (event) => {
  const payload = event.data.json();
  // 优先读取notification字段,兼容纯数据消息和混合消息
  const title = payload.notification?.title || payload.data?.title;
  const body = payload.notification?.body || JSON.parse(payload.data?.body).content;
  
  const options = {
    body: body,
    icon: "/logo.png",
  };

  event.waitUntil(self.registration.showNotification(title, options));
});

方法2:保持纯数据消息,在React Native客户端手动处理

若坚持发送纯数据消息,需在React Native项目中配置消息监听并手动构建通知:

  1. 确保已正确安装@react-native-firebase/messaging和@react-native-firebase/app依赖,并完成原生端配置。
  2. 注册消息监听:
import messaging from '@react-native-firebase/messaging';
import PushNotification from 'react-native-push-notification';

// 监听前台收到的消息
messaging().onMessage(async remoteMessage => {
  const bodyData = JSON.parse(remoteMessage.data.body);
  PushNotification.localNotification({
    title: remoteMessage.data.title,
    message: bodyData.content,
    // 可添加更多自定义配置
  });
});

// 监听应用后台/关闭时收到的消息
messaging().setBackgroundMessageHandler(async remoteMessage => {
  const bodyData = JSON.parse(remoteMessage.data.body);
  PushNotification.localNotification({
    title: remoteMessage.data.title,
    message: bodyData.content,
  });
});

注:后台消息处理需完成对应原生端配置(如Android后台服务、iOS推送权限),且需依赖第三方通知库(如react-native-push-notification)来手动触发系统通知。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 11:25:06