React Native WebView onMessage 不做任何事情 [英] React Native WebView onMessage doesn't do anything

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

问题描述

我正在尝试使用 onMessage 侦听器.该网站正在执行 postMessage (window.postMessage("Post message from web");) 但本机的 webview onMessage 侦听器没有做任何事情!我不知道我做错了什么.

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.

这是 HTML

<script type="text/javascript">
  window.postMessage("Post message from web");
</script>

这里是 react-native 代码:

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 反应原生函数:

onMessage react native function:

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

这里也有世博小吃...我不知道我做错了(:...https://snack.expo.io/S17AQqWbf

Here is an expo snack too... I don't know that I'm doing wrong (: ... https://snack.expo.io/S17AQqWbf

推荐答案

根据这个issue,你需要等到 React Native postMessage 替换了原生的 window.postMessage(不要问我为什么他们正在替换本机函数而不是创建新函数).

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天全站免登陆