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

React Native中WebView替代@javascriptInterface的方案及导入问题咨询

Fixing React Native WebView JS-Native Bridge (Replacing Android's addJavaScriptInterface)

Hey there! Let's get this sorted for you. The react-native-webview-bridge library is long unmaintained, which is why you're running into that import failure. Instead, you should use the official react-native-webview package—it's actively maintained and fully supports the JS-native communication you need to replace your Android app's addJavaScriptInterface setup.

Here's a step-by-step implementation that mirrors your original Android functionality:

1. Install the Official WebView Dependency

First, replace the outdated bridge library with the official one:

npm install react-native-webview --save
# Or use yarn if that's your preference
yarn add react-native-webview

For React Native 0.60+, auto-linking handles the native setup automatically. If you're on an older version, you'll need to manually link the package, but that's rare these days.

2. Implement RN Side: Listen for Web Calls & Expose Bridge Methods

This code replicates the behavior of your Android @javascriptbridge annotated methods. We'll listen for messages from the WebView and map them to native RN functions, plus inject a global Android object into the web page to match your original API:

import React, { useCallback, useRef } from 'react';
import { WebView } from 'react-native-webview';

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

  // Handle messages sent from the web page to RN
  const handleWebMessage = useCallback((event) => {
    const message = JSON.parse(event.nativeEvent.data);
    
    // Route the call to the corresponding RN method
    switch (message.type) {
      case 'invokeNativeMethod1':
        handleNativeMethod1(message.params);
        break;
      case 'invokeNativeMethod2':
        handleNativeMethod2(message.params);
        break;
      default:
        console.warn(`Unknown message type: ${message.type}`);
    }
  }, []);

  // Your original Android method1 logic goes here
  const handleNativeMethod1 = (params) => {
    console.log('Web called method1 with params:', params);
    // Send a response back to the web page if needed
    webViewRef.current?.postMessage(JSON.stringify({
      type: 'method1Response',
      data: 'Success! Method1 processed your request.'
    }));
  };

  // Your original Android method2 logic goes here
  const handleNativeMethod2 = (params) => {
    console.log('Web called method2 with params:', params);
  };

  return (
    <WebView
      ref={webViewRef}
      // Replace with your web page URL or local file path
      source={{ uri: 'https://your-web-page-url.com' }}
      javaScriptEnabled={true}
      // Listen for messages from the web page
      onMessage={handleWebMessage}
      // Inject a global `Android` object into the web page (matches your original API)
      injectedJavaScriptBeforeContentLoaded={`
        window.Android = {
          method1: function(params) {
            window.ReactNativeWebView.postMessage(JSON.stringify({
              type: 'invokeNativeMethod1',
              params: params
            }));
          },
          method2: function(params) {
            window.ReactNativeWebView.postMessage(JSON.stringify({
              type: 'invokeNativeMethod2',
              params: params
            }));
          }
        };
        // Notify the web page the bridge is ready
        window.postMessage('AndroidBridgeReady');
      `}
    />
  );
};

export default CustomWebView;

3. Web Page Side: Keep Your Existing Calls (No Major Changes!)

Your web page's existing code can stay almost identical—we've injected the same Android global object you used on Android:

// Your original web code works as-is
Android.method1({ userId: 456, action: 'update' });
Android.method2('Hello from the web!');

// Optional: Listen for responses from RN
window.addEventListener('message', (event) => {
  const response = JSON.parse(event.data);
  if (response.type === 'method1Response') {
    console.log('RN sent back:', response.data);
  }
});

Why react-native-webview-bridge Failed

That library hasn't been updated since 2018, so it's incompatible with modern React Native versions (0.60+). The official react-native-webview is the standard now, with full support for both iOS and Android.

Quick Notes

  • Always use JSON to serialize messages between web and RN to avoid parsing errors.
  • For local web files, use source={{ uri: 'file:///android_asset/your-page.html' }} (Android) or source={{ uri: 'bundle://your-page.html' }} (iOS).
  • On iOS, if loading HTTP (not HTTPS) pages, you'll need to adjust App Transport Security settings in Info.plist.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:55:13