RN Webview与Web的通讯与调试

原文连接:https://mrzhang123.github.io/...html

React Native Version:0.51

RN 在 0.37 版本中加入了WebView功能,因此想要在使用WebView,版本必须>=0.37,发送的 message 只能是字符串,因此须要将其余格式的数据转换成字符串,在接收到后再转换回去,其实直接用JSON.stringifyJSON.parse就能够git

加载 html

source属性用于指定加载的 html,能够加载在线的页面,也能够加载本地的页面,代码以下:github

// 加载线上页面
<Webview
    source={{uri: 'http://www.mi.com'}}
/>
// 加载本地html文件
<WebView
    source={require('../src/html/index.html')}
/>

注意 ⚠️

在 RN 中能够加载 WebView,可是没法调试,也不能使用 alert 来验证代码 js 代码是否运行成功,只能经过往 html 写入东西(innerHTML)来验证 js 是否运行成功web

WebView 与 html 的通讯

webview 发送信息到 html

WebView 给 html 发送信息须要使用postMessage,而 html 接收 RN 发过来的信息须要监听message事件,代码以下:chrome

// RN
class WebViewExample extends Component {
  onLoadEnd = () => {
    this.refs.webview.postMessage = 'this is RN msg'
  }
  render() {
    return (
      <WebView
        ref="webview"
        source={require('../html/index.html')}
        onLoadEnd={this.onLoadEnd}
      />
    )
  }
}
export default WebViewExample
// web
window.document.addEventListener('message', function(e) {
  const message = e.data
})

这里须要注意一点post

postMessage须要在 webview 加载完成以后再去 post,若是放在commponentWillMount里因为页面没有加载完成就 post 信息,会致使 html 端没法监听到 message 事件。ui

html 发送信息到 webview

// RN
class WebViewExample extends Component {
  handleMessage = e => {
    const message = e.nativeEvent.data
  }
  render() {
    return (
      <WebView
        ref="webview"
        source={require('../html/index.html')}
        onMessage={e => this.handleMessage(e)}
      />
    )
  }
}
export default WebViewExample

// web
window.postMessage('this is html msg')

debug

RN 中 debug webview 和安卓开发中看起来是差很少的,链接好设备后,在 chrome 中输入this

chrome://inspect

就能够看到安卓设备上正在运行的 webview 了,点击inspect就会开启一个调试页面,就能够进行 debug 了,RN 彷佛默认开启了 debug 调试,直接就能够看到 webview 中输出的信息。spa

clipboard.png

可是我发现我打开的调试界面是一个错乱的界面,不知道为何,无奈--!debug

clipboard.png

注意 ⚠️

这里须要注意一点的,因为安卓版本的差别,因此内部的 webview 对 js 的支持程度也不一样,为了保证兼容性,若是使用了 ES6,请转成 ES5,不然会报错。

相关文章
相关标签/搜索