React Native WebView onMessage不会执行任何操作 [英] React Native WebView onMessage doesn't do anything

查看:677
本文介绍了React Native WebView onMessage不会执行任何操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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:'https://app.sodge.co/login/response.html'}}
/>

onMessage反应原生函数:

<$ p $ (
Alert.alert(
'On Message',
event.nativeEvent.data,
[
{ text:'OK'},
],
{cancelable:true}

}

这里还有一个世博小吃......我不知道我做错了(:...
https://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: 'https://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 (: ... https://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不会执行任何操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆