使用react-native-webview实现RN和H5中iframe的通讯

先说说业务场景,在A.html中使用iframe引入了B.html,如今须要在APP中使用webview引入A.html,而且在点击B.html页面的某一处与RN进行通讯。查看react-native-webview的RN和web页面的通讯,通讯时官方文档和插件是有区别的。javascript

html向RN发送信息:html

window.ReactNativeWebView.postMessage(msg)复制代码

RN向H5发信息
java

const run = ` true;`;setTimeout(() => {this.webview.injectJavaScript(run);//RN经过向H5页面添加js的方法向H5页面传递信息}, 3000);return(<View style={{flex:1,backgroundColor: '#fcfcfc',paddingTop:20}}><WebView      source={{uri: 'http://192.168.21.123:88/'}}      style={{marginTop: 20}}      javaScriptEnabled={true}     startInLoadingState={true}     ref={(webview) => { this.webview = webview; }}     onMessage={(event) => {       alert(event.nativeEvent.data)      }) }}       onLoadEnd={() => {        this.webview.postMessage('RN向H5发送的消息');  }} />)复制代码

可是咱们的业务场景是点击在A.html中的B.html进行通讯,这个时候就要在A和B两个页面通讯;react

A.html:git

<body><div>我就是一个栗子</div><iframe src="btn.html" frameborder="0"></iframe></body><script type="text/javascript">      function getMsg(msg) {               window.ReactNativeWebView.postMessage(msg)      }</script>复制代码

B.html
github

<body><div class="btn">点我发送消息</div></body><script>        $('.btn').click(function () {                window.parent.getMsg('我是iframe')           });</script>复制代码
相关文章
相关标签/搜索