WebView和H5相互发送监听消息
1.1 Rn向h5发送消息
a. rn 发消息给你h5
<WebView source={ { uri: `${ENVIRONMENT[GLOBAL.CURR_ENV].logistics}?token=${GLOBAL.TOKEN}` }} ref={webview => this.webview = webview} onMessage={this._getH5Data} onLoadEnd={ () => { this.refs.webView.postMessage('RN向H5发送的消息'); //主意 一定是字符串传输 } } useWebKit={true} onError={this._errorFn} startInLoadingState={true} />
b. 在H5中注册监听
window.onload = function() { document.addEventListener('message', function(msg) { console.log(msg) message = msg.data; }); }
1.2 H5向RN发送消息
a. 在RN端通过onMessage接收消息
<WebView
source={
{ uri: `${ENVIRONMENT[GLOBAL.CURR_ENV].logistics}?token=${GLOBAL.TOKEN}` }
}
ref={webview => this.webview = webview}
onMessage={(event) => {console.log(event.nativeEvent.data);}}
onLoadEnd={this._sendH5}
useWebKit={true}
onError={this._errorFn}
startInLoadingState={true}
/>
b. H5发送消息,此时只能传递string类型
window.postMessage('网页向rn发送的消息');