美文网首页
react-native WebView与h5交互

react-native WebView与h5交互

作者: sybil052 | 来源:发表于2019-07-10 18:17 被阅读0次

公司一个项目使用react-native搭了app的架子,使用WebView加载h5实现UI界面,同时h5和app需要做很多交互,今天就来说一下两者的交互问题。

一、react-native WebView和h5相互发送消息

(一)h5向react-native WebView发消息
  1. h5发送消息,只能传递string类型
data={
    "Name":"getUserId",
    "userId":"1234567890"
};
window.postMessage(JSON.stringify(data), '*');
  1. react-native中接收消息
    网页端的 window.postMessage 只发送一个参数 data,此参数封装在 react-native端的 event 对象中,即 event.nativeEvent.data。data 只能是一个字符串。
_handlerMessage(evt) {
    let action = JSON.parse(evt.nativeEvent.data);
    switch (action.Name) {
        case "getUserId" : {
            console.log("获取userId",evt.nativeEvent.data);
            break;
        }
    }
}
...
<WebView
    style={webViewStyle}
    source={{uri: this.state.url}}
    scalesPageToFit={Platform.OS === 'ios'}
    javaScriptEnabled={true}
    injectedJavaScript={onMessage}
    ref='webView'
    onMessage={(event) => this._handlerMessage(event)}
 />
...
(二)react-native WebView向h5发消息
  1. react-native发送消息
    首先WebView要绑定ref='webView',然后执行this.refs['webView'].postMessage('发送消息');
let message = `{"Name":"selectPhoto","url":"${result.data}"}`;
console.log("选择图片",  message);
this.refs['webView'].postMessage(message);
  1. h5中接收消息
    h5在加载的时候注册监听,监听message

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

function selectPhoto(){
    window.document.addEventListener('message', function( message ){
        let action = JSON.parse(message.data);
        if(action.Name == "selectPhoto"){
            console.log("图片地址",  action.url);
        }
    });
}

二、react-native WebView向h5注入js

react-native WebView的injectedJavaScript属性可以设置 js 字符串,在网页加载之前注入的一段 js 代码。

  let message = `document.addEventListener('message', function( message ){
      let action = JSON.parse(message.data);
      if(action.Name == "goBackHome"){
        location.href = action.url;
      }
    })`
  ...
  <WebView
      style={webViewStyle}
      source={{uri: this.state.url}}
      scalesPageToFit={Platform.OS === 'ios'}
      javaScriptEnabled={true} // 控制是否启用 JavaScript
      injectedJavaScript={message}
      ref='webView'
      onMessage={(event) => this._handlerMessage(event)}
   />
  ...
  reload(){
      let message = `{"Name":"goBackHome","url":"${this.state.url}"}`;
      console.log("返回首页地址", typeof(message));
      this.refs['webView'].postMessage(message);
  }

相关文章

网友评论

      本文标题:react-native WebView与h5交互

      本文链接:https://www.haomeiwen.com/subject/anuhkctx.html