繁体   English   中英

反应原生html postMessage无法访问WebView

[英]react native html postMessage can not reach to WebView

我使用React Native webview来显示index.html ,HTML将在应用程序中发布消息。 然后,应用程序将接收消息并将其写入控制台。 问题是当postMessage立即在头上运行时,app无法接收消息。 我认为它可能与HTML没有完成加载有关。 然后我使用setTimeout延迟,它工作。

现在我想知道:

  • 有没有更好的方法来解决这个问题?
  • 为什么延迟100毫秒不起作用,但延迟200毫秒呢?

我使用的是React Native版本0.39.0和Node版本7.2.0。

这是我到目前为止的代码:

的index.html

<head>
<title>Index</title>
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript">
    // can not be received
    postMessage('send to react native from index inline, no delay', '*');

    // can not be received
    setTimeout(function(){
        postMessage('send to react native from index inline, delay 0 milliscond', '*')
    }, 0);

    // can received
    setTimeout(function(){
        postMessage('send to react native from index inline, delay 100 milliscond', '*')
    }, 100);

    onload = function() {
        // can not be received
        postMessage('send to react native from index inline after onload, no delay', '*')

        // can received
        setTimeout(function () {
            postMessage('send to react native from index inline after onload, delay 0 milliscond', '*')
        }, 0);
    };
</script>

index.js

// can not be received
postMessage('send to react native from index.js, no delay', '*');

// can not be received
setTimeout(function() {
    postMessage('send to react native from index.js, delay 100 milliscond', '*')
}, 100);

// can received
setTimeout(function() {
    postMessage('send to react native from index.js, delay 200 milliscond', '*')
}, 200);

React Native web_view_page.js

return (
        <WebView
            source={{uri: 'http://127.0.0.1:8000/index.html'}}
            onMessage={(event) => console.log('onMessage:', event.nativeEvent.data)}/>
    );

Chrome控制台日志

2016-12-21 11:45:02.367 web_view.js:147 onMessage: send to react native from index inline after onload, delay 0 milliscond
2016-12-21 11:45:02.491 web_view.js:147 onMessage: send to react native from index inline, delay 100 milliscond
2016-12-21 11:45:02.628 web_view.js:147 onMessage: send to react native from index.js, delay 200 milliscond

我相信你现在已经找到了答案,但是如果你没有或者有其他人需要,请查看https://github.com/facebook/react-native/issues/11594

基本上,您需要等待postMessage出现在窗口中才能成功发布消息。

function onBridgeReady(cb) {
  if (window.postMessage.length !== 1) {
    setTimeout(function() {
      onBridgeReady(cb)
    }, 100);
  } else {
    cb();
  }
}

onBridgeReady(function() {
  window.postMessage('Bridge is ready and WebView can now successfully receive messages.');
});

资料来源: Andrei Barabas

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM