React-Native Webview 和H5交互的两种方式

React-Native WebView 和H5交互有两种方式:

方式1:RN Webview 向H5注入JS

此方式可作为Webview向H5端传递数据。
RN Webview 有以下属性,可以注入一段js,然后在相应的时间调用。
injectedJavaScript 设置 js 字符串,在网页加载之前注入的一段 JS 代码。

类型 必填
string

思路:通过injectedJavaScript 注入JS ,在H5页面加载之后立即执行。相当于webview端主动调用H5的方法。
这里有个注意点,injectedJavaScript注入的必须是js。注入的内容可以是方法实现,也可以是方法名字
需要说明
1.其实注入函数名的时候,实际上注入的仍然是函数实现
2.当注入js方法名需要传递参数的时候,可提前将函数名作为字符串,函数参数作为变量,生成一个字符串,然后将此字符串注入。

H5端




    
    Title








RN端

    render() {
        let text = this.props.navigation.state.params.authInfo;
        let text1 = `yyy('${text}')`;
        console.log(text1);
        return (
            
                \n' +
                             '\n' +
                             '\n' +
                             '\n' +
                             '\n' +
                             ''
                         }}

                    // onLoadEnd={() => {
                    //      this.refs.webView.postMessage(this.props.navigation.state.params.authInfo);
                    // }}
                >
                
            
        );
    }

这种方式和OC中WKWebView注入JS的原理基本一致。

方式2:Webview 和 H5 相互发送监听消息

该方式可双向发送数据信息。

(1)RN端向H5发送消息

首先Webview绑定ref={webview => this.webview = webview}

onLoadEnd={() => {
 this.refs.webView.postMessage('RN向H5发送的消息');
 }}

也可可在其他任意地方获取webview,执行this.webview.postMessage('RN向H5发送的消息');
H5在加载的时候注册监听。

H5 监听message 注意这个监听的名字只能叫message。

in Android

window.onload = function() {
document.addEventListener("message", function(event) {
       alert("This is a Entry Point Working in android");
       init(event.data)
  });
}

in iOS

window.onload = function() {
     windows.addEventListener("message", function(event) {
       alert("This is a Entry Point Working in iOS");
       init(event.data)
  });
 }


(2)H5向RN发送消息

RN Webview onMessage 属性

在 webview 内部的网页中调用 window.postMessage 方法时可以触发此属性对应的函数,从而实现网页和 RN 之间的数据交换。 设置此属性的同时会在 webview 中注入一个 postMessage 的全局函数并覆盖可能已经存在的同名实现。

网页端的 window.postMessage 只发送一个参数 data,此参数封装在 RN 端的 event 对象中,即 event.nativeEvent.data。data 只能是一个字符串。

webview 组件 在被官方放弃之后,react-native-webview 作为替换。react-native-webview 5.0 之后需要注入js

https://github.com/react-native-community/react-native-webview/releases/tag/v5.0.0
需要注入以下这段js 用以替换window.postMessage. H5 使用方法不变。

const injectedJavascript = `(function() {
  window.postMessage = function(data) {
    window.ReactNativeWebView.postMessage(data);
  };
})()`;
类型 必填
function

实现过程:

H5发送消息,此时只能传递string类型

window.postMessage('网页向rn发送的消息');

react-native中接收消息

onMessage={(event) => {console.log(event.nativeEvent.data);}}

你可能感兴趣的:(React-Native Webview 和H5交互的两种方式)