RN Webview与Web的通信与调试

本文介绍了React Native中WebView组件的使用方法,包括加载线上和本地HTML页面、实现RN与HTML之间的消息传递,以及如何进行调试。

原文链接:mrzhang123.github.io/2017/12/20/…

React Native Version:0.51

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

加载 html

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

// 加载线上页面
<Webview
	source={{uri: 'http://www.mi.com'}}
/>
// 加载本地html文件
<WebView
	source={require('../src/html/index.html')}
/>
// 或者
<WebView
	source={{uri: 'file:///android_asset/baiduMap/index.html'}}
	onMessage={e => this.handleMessage(e)}
	automaticallyAdjustContentInsets={false}
	startInLoadingState
/>
复制代码
注意 ⚠️

加载本地html的方式虽然可以使用require也可以使用uri: 'file:///android_asset/baiduMap/index.html'的形式,但是在实际开发中发现,使用require在打成包之后无法加载到。所以将html放在assets文件夹下,使用file路径加载:

  1. 将html文件放在android/app/src/main/assets
  2. 加载html,即source={{uri: 'file:///android_asset/baiduMap/index.html'}}

WebView 与 html 的通信

webview 发送信息到 html

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

// 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
})
复制代码

这里需要注意一点

postMessage需要在 webview 加载完成之后再去 post,如果放在commponentWillMount里由于页面没有加载完成就 post 信息,会导致 html 端无法监听到 message 事件。

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 中输入

chrome://inspect
复制代码

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

但是我发现我打开的调试界面是一个错乱的界面,不知道为什么,无奈。

注意 ⚠️

这里需要注意一点的,由于安卓版本的差异,所以内部的 webview 对 js 的支持程度也不同,为了保证兼容性,如果使用了 ES6,请转成 ES5,否则会报错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值