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

如何在React Native WebView应用中将FCM网页推送转为应用通知

实现WebView中网页FCM推送转React Native应用级通知(无需完整集成RN FCM)

核心思路是利用WebView的消息通信机制:让网页端在收到FCM推送时,将通知数据传递给React Native原生层,再由RN调用系统通知API显示应用级通知,全程不需要在RN中集成FCM SDK。

步骤1:改造网页端FCM消息处理逻辑

在你的Next.js网页中,修改FCM的推送监听代码,判断当前是否处于React Native WebView环境,若是则将通知数据通过postMessage传给RN,同时可按需阻止网页自身显示通知。

// 网页端FCM推送监听
self.addEventListener('push', (event) => {
  const payload = event.data?.json() || {};
  // 提取通知核心数据
  const notificationPayload = {
    title: payload.notification?.title || '新通知',
    body: payload.notification?.body || '',
    extraData: payload.data || {}
  };

  // 判断是否在RN WebView中
  if (window.ReactNativeWebView) {
    // 序列化后发送给RN
    window.ReactNativeWebView.postMessage(JSON.stringify(notificationPayload));
    // 阻止网页默认弹出通知(如果不需要网页端显示)
    event.preventDefault();
  } else {
    // 非WebView环境,正常显示网页通知
    event.waitUntil(
      self.registration.showNotification(notificationPayload.title, {
        body: notificationPayload.body,
        ...notificationPayload.extraData
      })
    );
  }
});

步骤2:React Native端接收消息并显示本地通知

使用成熟的RN本地通知库(比如react-native-push-notification),在WebView中监听message事件,收到网页传来的通知数据后,调用本地通知API显示应用级通知。

安装依赖

npm install react-native-push-notification
# 或
yarn add react-native-push-notification

核心代码实现

import React, { useEffect, useRef } from 'react';
import { WebView } from 'react-native-webview';
import PushNotification from 'react-native-push-notification';

const WebViewWithNotification = () => {
  const webViewRef = useRef(null);

  // 初始化本地通知配置
  useEffect(() => {
    PushNotification.configure({
      // 处理通知点击事件
      onNotification: (notification) => {
        console.log('通知点击:', notification);
        // 可选:让网页跳转到对应页面
        webViewRef.current?.injectJavaScript(`window.handleNotificationClick(${JSON.stringify(notification.userInfo)})`);
      },
      // 请求通知权限
      requestPermissions: true,
      permissions: {
        alert: true,
        badge: true,
        sound: true
      }
    });

    return () => {
      // 组件卸载时清除所有本地通知
      PushNotification.cancelAllLocalNotifications();
    };
  }, []);

  // 处理WebView传来的消息
  const handleWebMessage = (event) => {
    try {
      const notificationData = JSON.parse(event.nativeEvent.data);
      // 触发本地通知
      PushNotification.localNotification({
        title: notificationData.title,
        message: notificationData.body,
        userInfo: notificationData.extraData, // 携带额外数据
        soundName: 'default', // 启用默认通知音效
        vibrate: true // 启用震动
      });
    } catch (error) {
      console.error('解析通知数据失败:', error);
    }
  };

  return (
    <WebView
      ref={webViewRef}
      source={{ uri: '你的Next.js网页地址' }}
      onMessage={handleWebMessage}
      javaScriptEnabled={true} // 必须开启,FCM和postMessage依赖
      domStorageEnabled={true} // 开启DOM存储,确保FCM正常工作
    />
  );
};

export default WebViewWithNotification;

关键注意事项

  • WebView配置:必须开启javaScriptEnabled和domStorageEnabled,否则网页端FCM无法正常运行,也无法和RN通信。
  • 平台权限配置:
    • iOS:在Info.plist中添加通知权限描述(NSAlertUsageDescription、NSBadgeUsageDescription等)。
    • Android:在AndroidManifest.xml中配置通知渠道、权限声明,具体可参考react-native-push-notification的配置说明。
  • 通知点击跳转:如果需要点击通知后跳转到网页指定页面,可在网页端预定义handleNotificationClick函数,RN端通过injectJavaScript触发该函数。
  • 兼容性:确保网页端的FCM Service Worker正常注册,且在WebView中能正常接收推送。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 08:44:55