react-native WebView 与 h5网页交互

h5网页向react-native发消息

  • 网页事件中发送消息window.postMessage('网页向rn发送的消息');
  • react-native中接收消息webview实现onMessage={this.handleMessage}方法,该方法中的e.nativeEvent.data就是网页传过来的消息handleMessage(e) {console.log(e.nativeEvent.data)}
  • 注意这里的传至只能是string

react-native网页向h5发消息

  • 首先webview绑定ref={webview => this.webview = webview}
  • 自定义一个点击事件,点击时执行this.webview.postMessage('rn向网页发送的消息');
  • 网页加在时进行监听e.data就为rn发送过来的消息
window.onload = function() {
        document.addEventListener('message', function(e) {     
            console.log(e.data)       
    });

遇到的一个小问题Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined.

  • 在网上查看的说postMessage被覆盖了,或者网页重写Iframe等情况也会导致,毕竟不是专业的,具体原因还说不清楚,最终参考https://github.com/facebook/react-native/issues/10865找到了解决办法
  • 使用injectedJavaScript方法在webview加在前注入一段JS代码patchPostMessageJsCode
const patchPostMessageFunction = function() {
    var originalPostMessage = window.postMessage;

    var patchedPostMessage = function(message, targetOrigin, transfer) {
        originalPostMessage(message, targetOrigin, transfer);
    };

    patchedPostMessage.toString = function() {
        return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
    };

    window.postMessage = patchedPostMessage;
};

const patchPostMessageJsCode = '(' + String(patchPostMessageFunction) + ')();';
  • webview加载时注入<WebView injectedJavaScript={patchPostMessageJsCode}/>就可以解决这个问题

推荐阅读更多精彩内容