【发布时间】:2017-05-06 11:45:25
【问题描述】:
我使用 React Native webview 来显示index.html,HTML 会将消息发布到应用程序。然后应用程序将收到消息并将其写入控制台。问题是应用程序无法接收消息,当postMessage 立即运行时。我认为这可能与 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
【问题讨论】:
标签: javascript html webview react-native postmessage