Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 537
MoO Avatar asked Jun 24 '19 13:06

MoO


1 Answers

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

React-native version 5.0 or later

window.ReactNativeWebView.postMessage(event.data);
like image 127
hong developer Avatar answered Sep 27 '22 23:09

hong developer