23mofang-react-native-webview-bridge 中文文档教程

发布于 7年前 浏览 21 项目主页 更新于 3年前

Please take a look at this issue first

React Native WebView Javascript Bridge

我一直在测试和阅读很多方法来安全地在 react-native 和 webview 之间建立桥梁。 我很高兴地宣布等待已经结束,从 React-Native 0.20 及更高版本 开始,该桥已完全正常运行。

Installation

为了使用此扩展,您必须执行以下步骤:

在您的 react-native 项目中,运行 npm install react-native-webview-bridge --save

iOS

  1. go to xcode's Project Navigator tab

  1. right click on Libraries
  2. select Add Files to ... option

  1. navigate to node_modules/react-native-webview-bridge/ios and add React-Native-Webview-Bridge.xcodeproj folder

  1. on project Project Navigator tab, click on your project's name and select Target's name and from there click on Build Phases

  1. expand Link Binary With Libraries and click + sign to add a new one.
  2. select libReact-Native-Webviwe-Bridge.a and click Add button.

  1. clean compile to make sure your project can compile and build.

Android

  1. add the following import to MainApplication.java (MainActivity.java if RN < 0.29) of your application
import com.github.alinz.reactnativewebviewbridge.WebViewBridgePackage;
  1. add the following code to add the package to MainApplication.java`` (MainActivity.java` if RN < 0.29)
protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
                new WebViewBridgePackage() //<- this
        );
    }
  1. add the following codes to your android/setting.gradle

您可能有多个第 3 方库,请确保您没有创建多个包含。

include ':app', ':react-native-webview-bridge'
project(':react-native-webview-bridge').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-webview-bridge/android')
  1. edit android/app/build.gradle and add the following line inside dependencies
compile project(':react-native-webview-bridge')
  1. run react-native run-android to see if everything is compilable.

Usage

只需使用您选择的一种方式导入模块:

** CommonJS 样式 **

var WebViewBridge = require('react-native-webview-bridge');

ES6/ES2015 样式 **

import WebViewBridge from 'react-native-webview-bridge';

WebViewBridgeWebView 的扩展。 一旦加载,它就会将特殊脚本注入任何页面。 它还通过添加 1 个新方法和 1 个新道具扩展了 WebView 的功能。

sendToBridge(message)

消息必须是字符串。 因为这是在 native 和 webview 之间来回发送数据的唯一方法。

onBridgeMessage

这是一个需要成为功能的道具。 一旦从 webview 收到消息,它将被调用。 接收到的消息类型也是字符串。

allowFileAccessFromFileURLs (Android only)

这是一个允许通过 file:// 本地加载的页面访问其他 file:// 资源的道具。 传递到 WebView 中相应的设置。 对于 Android 4.1 及更高版本,默认值为 false

allowUniversalAccessFromFileURLs (Android only)

这是一个允许通过 file:// 本地加载的页面访问任何来源的资源的道具。 传递到 WebView 中相应的设置。 对于 Android 4.1 及更高版本,默认值为 false

Bridge Script

bridge 脚本是一个特殊的脚本,它注入所有的 webview。 它会自动注册一个名为 WebViewBridge 的全局变量。 它有 2 个可选的实现方法和一个向本机端发送消息的方法。

send(message)

此方法向本机端发送消息。 消息必须是字符串类型,否则将调用 onError 方法。

onMessage

这个方法需要实现。 一旦消息从本机端到达,它将被调用。 消息的类型是字符串。

onError (iOS only)

这是一种错误报告方法。 如果在发送消息过程中发生错误,它将被调用。 它收到字符串类型的错误消息。

Notes

一旦页面转到不同的 URL,就会注入一个特殊的桥接脚本。 因此,您无需管理何时需要注入。

您仍然可以传递自己的 javascript 以注入到 webview 中。 但是,将首先注入 Bridge 脚本,然后注入您的自定义脚本。

Simple Example

这个例子可以在 examples 文件夹中找到。

const injectScript = `
  (function () {
                    if (WebViewBridge) {

                      WebViewBridge.onMessage = function (message) {
                        if (message === "hello from react-native") {
                          WebViewBridge.send("got the message inside webview");
                        }
                      };

                      WebViewBridge.send("hello from webview");
                    }
                  }());
`;

var Sample2 = React.createClass({
  onBridgeMessage(message){
    const { webviewbridge } = this.refs;

    switch (message) {
      case "hello from webview":
        webviewbridge.sendToBridge("hello from react-native");
        break;
      case "got the message inside webview":
        console.log("we have got a message from webview! yeah");
        break;
    }
  },

  render() {
    return (
      <WebViewBridge
        ref="webviewbridge"
        onBridgeMessage={this.onBridgeMessage.bind(this)}
        injectedJavaScript={injectScript}
        source={{uri: "http://google.com"}}/>
    );
  }
});

Please take a look at this issue first

React Native WebView Javascript Bridge

I have been testing and reading a lot of way to safely create a bridge between react-native and webview. I'm happy to announced that the wait is over and from React-Native 0.20 and above, the bridge is fully functional.

Installation

In order to use this extension, you have to do the following steps:

in your react-native project, run npm install react-native-webview-bridge --save

iOS

  1. go to xcode's Project Navigator tab

  1. right click on Libraries
  2. select Add Files to ... option

  1. navigate to node_modules/react-native-webview-bridge/ios and add React-Native-Webview-Bridge.xcodeproj folder

  1. on project Project Navigator tab, click on your project's name and select Target's name and from there click on Build Phases

  1. expand Link Binary With Libraries and click + sign to add a new one.
  2. select libReact-Native-Webviwe-Bridge.a and click Add button.

  1. clean compile to make sure your project can compile and build.

Android

  1. add the following import to MainApplication.java (MainActivity.java if RN < 0.29) of your application
import com.github.alinz.reactnativewebviewbridge.WebViewBridgePackage;
  1. add the following code to add the package to MainApplication.java`` (MainActivity.java` if RN < 0.29)
protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
                new WebViewBridgePackage() //<- this
        );
    }
  1. add the following codes to your android/setting.gradle

you might have multiple 3rd party libraries, make sure that you don't create multiple include.

include ':app', ':react-native-webview-bridge'
project(':react-native-webview-bridge').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-webview-bridge/android')
  1. edit android/app/build.gradle and add the following line inside dependencies
compile project(':react-native-webview-bridge')
  1. run react-native run-android to see if everything is compilable.

Usage

just import the module with one of your choices way:

** CommonJS style **

var WebViewBridge = require('react-native-webview-bridge');

** ES6/ES2015 style **

import WebViewBridge from 'react-native-webview-bridge';

WebViewBridge is an extension of WebView. It injects special script into any pages once it loads. Also it extends the functionality of WebView by adding 1 new method and 1 new props.

sendToBridge(message)

the message must be in string. because this is the only way to send data back and forth between native and webview.

onBridgeMessage

this is a prop that needs to be a function. it will be called once a message is received from webview. The type of received message is also in string.

allowFileAccessFromFileURLs (Android only)

this is a prop that allows locally loaded pages via file:// to access other file:// resources. Pass-thru to corresponding setting in WebView. Default is false for Android 4.1 and above.

allowUniversalAccessFromFileURLs (Android only)

this is a prop that allows locally loaded pages via file:// to access resources in any origin. Pass-thru to corresponding setting in WebView. Default is false for Android 4.1 and above.

Bridge Script

bridge script is a special script which injects into all the webview. It automatically register a global variable called WebViewBridge. It has 2 optional methods to implement and one method to send message to native side.

send(message)

this method sends a message to native side. the message must be in string type or onError method will be called.

onMessage

this method needs to be implemented. it will be called once a message arrives from native side. The type of message is in string.

onError (iOS only)

this is an error reporting method. It will be called if there is an error happens during sending a message. It receives a error message in string type.

Notes

a special bridge script will be injected once the page is going to different URL. So you don't have to manage when it needs to be injected.

You can still pass your own javascript to be injected into webview. However, Bridge script will be injected first and then your custom script.

Simple Example

This example can be found in examples folder.

const injectScript = `
  (function () {
                    if (WebViewBridge) {

                      WebViewBridge.onMessage = function (message) {
                        if (message === "hello from react-native") {
                          WebViewBridge.send("got the message inside webview");
                        }
                      };

                      WebViewBridge.send("hello from webview");
                    }
                  }());
`;

var Sample2 = React.createClass({
  onBridgeMessage(message){
    const { webviewbridge } = this.refs;

    switch (message) {
      case "hello from webview":
        webviewbridge.sendToBridge("hello from react-native");
        break;
      case "got the message inside webview":
        console.log("we have got a message from webview! yeah");
        break;
    }
  },

  render() {
    return (
      <WebViewBridge
        ref="webviewbridge"
        onBridgeMessage={this.onBridgeMessage.bind(this)}
        injectedJavaScript={injectScript}
        source={{uri: "http://google.com"}}/>
    );
  }
});
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文