React Native WebView onMessage不起作用

时间:2018-11-21 06:52:17

标签: react-native

我的同伴

import React, {Component} from 'react';
import {WebView} from 'react-native';

class Html extends Component {

    constructor(props){
      super(props);
      this.webView = null;
    }

    onMessage( event ) {
        console.log( "On Message", event.nativeEvent.data );
    }

    sendPostMessage(msg) {
        console.log( "Sending post message",msg );
        this.webView.postMessage(JSON.stringify(msg));
    }

    runJSInBackground (code) {
      this.webView.injectJavaScript(code)
    }


  render() {  
    return (
      <WebView
        originWhitelist={['*']}
        ref={( webView ) => this.webView = webView}
        onMessage={this.onMessage}
        onError={(e)=>console.log("WebView error: "+e)}
        source={{
          baseUrl:"include/",
          html: `
          <html>
              <head>
              </head>
            <body>
            <script>
            document.addEventListener("message",function(event) {
                console.log("Received post message", event); //Work!!!
            }, false);

            setTimeout(()=>window.postMessage("WhatsAppMANNN!!!"),5000) //doesn`t work ((
            </script>
            </body>
          </html>
          ` }}
      />
    )
  }

}

export default Html;

当我发送WebView请求时,一切正常,但返回的结果没有答案。也就是说,window.postMessage方法不起作用,并且该错误也不会点亮。有什么要害,不是我找不到这个问题的答案。

1 个答案:

答案 0 :(得分:0)

尝试使用:

window.postMessage("Lulz", "*") 

来源:https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage