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

React Native应用前台时点击推送通知如何获取跳转URL?

解决React Native前台点击FCM通知无响应的问题

核心原因

Linking.getInitialURL()仅适用于冷启动(应用完全关闭后打开)或从后台被通知唤醒的场景。当应用处于前台时,点击通知不会触发该方法,需要通过FCM的消息监听事件来处理。

解决方案

1. 配置FCM消息监听(覆盖前台/后台场景)

使用@react-native-firebase/messaging库的监听方法,直接捕获通知点击事件并处理跳转:

import messaging from '@react-native-firebase/messaging';
import Linking from 'react-native/Libraries/Linking/Linking';

// 监听通知点击事件(兼容前台、后台唤醒场景)
messaging().onNotificationOpenedApp(remoteMessage => {
  const deepLink = remoteMessage.data['gcm.n.link'];
  if (deepLink) {
    Linking.openURL(deepLink)
      .catch(err => console.error('跳转失败:', err));
  }
});

// 保留冷启动场景的原有逻辑
Linking.getInitialURL()
  .then((initialUrl) => {
    if (initialUrl) {
      Linking.openURL(initialUrl);
    }
  })
  .catch((err) => {
    console.log("获取初始URL失败:", err);
  });

2. 适配iOS前台通知展示(可选)

iOS默认在前台不会弹出系统通知,若需要前台也显示通知,需配置通知展示权限:

import { Platform } from 'react-native';
import messaging from '@react-native-firebase/messaging';

async function setupNotificationPermission() {
  const authStatus = await messaging().requestPermission();
  const enabled =
    authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
    authStatus === messaging.AuthorizationStatus.PROVISIONAL;

  if (enabled && Platform.OS === 'ios') {
    // 开启iOS前台通知展示
    messaging().setForegroundNotificationPresentationOptions({
      alert: true,
      badge: true,
      sound: true,
    });
  }
}

// 应用启动时调用权限配置
setupNotificationPermission();

3. 优化推送请求体(可选)

建议将跳转链接改用自定义键,避免依赖厂商特定字段,提升兼容性:

{
    "to": "token",
    "notification": {
        "body": "body",
        "title": "title",
        "subtitle": "subtitle"
    },
    "data": {
        "deepLink": "myApp://?screenName=TradeDetail"
    }
}

对应监听逻辑修改为:

const deepLink = remoteMessage.data.deepLink;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 02:56:19