How can I send a message from the WebView to React

2019-08-31 04:39发布

问题:

I’ve successfully managed to send a message from React Native (RN) to a WebView.

What I’m struggling with, is getting the message back from the WebView to RN. There’s no errors showing - it’s just that the message never gets through.

Here is the code which I’m using:

React Native Code

<WebView
  ref={webview => (this.webview = webview)}
  source={{ uri: "http://www.my-web-site"}}
  onLoadEnd={() => this.onLoadEnd()}
  onMessage={this.onMessage}
  cacheEnabled={false}
  originWhitelist={['*']}
  javaScriptEnabled={true}
/>

onLoadEnd() {
  this.webview.postMessage("RN message");
}

onMessage(message) {
  console.log("I can’t see this message!");
}

WebView Code

document.addEventListener("message", function (event) {
  setTimeout(function(){document.postMessage("WebView message")}, 3000);
}, false);

Many thanks in advance.

回答1:

Please make sure that the data for each receiver is in and use the data that You need.

And always check the prescribed documents to see how to use parameters and grammar before using them.

RN

onLoadEnd() {

  this.webview.postMessage("sendmessage");
}

onMessage(event) {
  alert(event.nativeEvent.data);
}

WebView Code

document.addEventListener("message", function (event) {
    window.postMessage(event.data);
});


回答2:

Oh, at last, I finally came across the answer. It was a line of code which I had originally been trying to use to send a message from RN to the WebView. Turns out, it was the code required for sending from the WebView to RN:

WebView Code

document.addEventListener("message", function (event) {
  window.ReactNativeWebView.postMessage(event.data);
}, false);