9
我使用React Native webview來顯示index.html
,HTML將嚮應用發佈消息。該應用程序將接收到消息並將其寫入控制檯。問題是應用程序無法接收消息,當postMessage
立即運行在頭上。我認爲它可能與HTML沒有完成加載有關。然後我用了setTimeout
的延遲,並且它工作。反應原生的html postMessage無法到達WebView
現在我想知道:
- 有沒有更好的辦法來解決這個問題?
- 爲什麼延遲100毫秒不起作用,但延遲200毫秒呢?
我正在使用React Native版本0.39.0和節點版本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);
陣營本地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