react-native: 0.59.9
react-native-webview: 5.6.2
android
在项目中遇到和第三方通信H5,使某个事件能够驱动react-native。根据文档在h5中使用 window.postMessage()方法就可触发RN当中的onMessage属性,在开发过程中,使用winow.postMessage()进行通信发现onMessage无法无法接收到postMessage发过来的消息。经查找发现需要再h5中需要使用
window.ReactNativeWebView.postMessage()
才可进行通信。具体代码如下
<WebView
javaScriptEnabled
source={{
html: `<body style="background: red">
<div id="test" style="background: yellow; height: 30">test====</div>
<script>
window.onload = function(){
var div = document.getElementById("test");
div.onclick=function(){
div.innerHTML="AFTER==";
window.ReactNativeWebView.postMessage(JSON.stringify({
home:true
}));
}
}
document.addEventListener('message',function(msg){
var div = document.getElementById("test");
div.innerHTML=msg.data;
});
</script>
</body>`
}}
onMessage={event => {
console.log('onMessage===', event.nativeEvent.data);
}}
/>