我正在尝试使用onMessage侦听器。该网站正在执行一个postMessage( window.postMessage(从网络发布消息); ),但是反应本地的webview onMessage监听器没有做任何事情!我不知道我在做什么错。
这是HTML
< script type =text / javascript> window.postMessage(从网络发布消息); < / script>以下是反应原生代码:
< WebView ref = {(webView)=> this.webView = webView} onMessage = {this.onMessage} source = {{uri:'app.sodge.co/login/response.html'}} />onMessage反应原生函数: <$ p $ ( Alert.alert('On Message', event.nativeEvent.data, [ { text:'OK'},], {cancelable:true} )}
这里还有一个世博小吃......我不知道我做错了(:... snack.expo.io/S17AQqWbf
解决方案根据这个问题,您需要等到React Native postMessage 取代了原生的 window.postMessage (别问我为什么 他们是替换原生函数而不是创建新函数)。
一种解决方案是执行类似以下操作:
函数waitForBridge() { //原本的反应postMessage只有一个参数 //默认的有2个参数,所以请检查 $的函数 if(window.postMessage.length!== 1){ setTimeout(waitForBridge,200); } else { window.postMessage('abc'); } } window.onload = waitForBridge;
I'm trying to use the onMessage listener. The website is executing a postMessage (window.postMessage("Post message from web");) but react native's webview onMessage listener is not doing anything! I don't know what I'm doing wrong.
Here is the HTML
<script type="text/javascript"> window.postMessage("Post message from web"); </script>And here is the react-native code:
<WebView ref={( webView ) => this.webView = webView} onMessage={this.onMessage} source={{uri: 'app.sodge.co/login/response.html'}} />onMessage react native function:
onMessage( event ) { Alert.alert( 'On Message', event.nativeEvent.data, [ {text: 'OK'}, ], { cancelable: true } ) }Here is an expo snack too... I don't know that I'm doing wrong (: ... snack.expo.io/S17AQqWbf
解决方案According to this issue, you need to wait until the React Native postMessage has replaced the native window.postMessage (don’t ask me why they are replacing a native function instead of creating a new one).
One solution is to do something like:
function waitForBridge() { //the react native postMessage has only 1 parameter //while the default one has 2, so check the signature //of the function if (window.postMessage.length !== 1){ setTimeout(waitForBridge, 200); } else { window.postMessage('abc'); } } window.onload = waitForBridge;
更多推荐
React Native WebView onMessage不会执行任何操作
发布评论