react native html postMessage can not reach to WebView
<p>I use React Native webview to show <code>index.html</code>, and HTML will post messge to the app. The app will then receive the message and write it to console. The problem is the app cannot receive messages, when <code>postMessage</code> is immediately run on head. I think it maybe related to HTML not finished loading. I then used a delay with <code>setTimeout</code>, and it worked.</p>

<p>Now I want to know:</p>

<ul>
<li>Is there better way to solve this problem?</li>
<li>Why the delay 100 milliscond did not work, but delay 200 milliscond did?</li>
</ul>

<p>I am using React Native version 0.39.0, and Node version 7.2.0.</p>

<p>Here is the code I have so far:</p>

<p>index.html</p>

<pre><code>&lt;head&gt;
&lt;title&gt;Index&lt;/title&gt;
&lt;script type="text/javascript" src="index.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
    // 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);
    };
&lt;/script&gt;
</code></pre>

<p></p>

<p>index.js</p>

<pre><code>// 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);
</code></pre>

<p>React Native web_view_page.js</p>

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

<p>Chrome console log</p>

<pre><code>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
</code></pre>