How can I send a message from the WebView to React Native?

感情迁移 提交于 2019-12-11 17:23:29

问题


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);


来源:https://stackoverflow.com/questions/56737292/how-can-i-send-a-message-from-the-webview-to-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!