U
U
UntitledNikname2020-05-28 12:55:08
React Native
UntitledNikname, 2020-05-28 12:55:08

How to communicate with the native environment through WebView?

For example, a page from www.example.com/myapp.html is loaded. There is nothing on this page except the included js file (built react application) with 1 method. How can you call a method from the Native among this method and get a response from it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Alexandrovich, 2020-05-28
@UntitledNikname

you need to use JavaScript custom method. Create html and function like

<!DOCTYPE html>
<html>
<head>
  <title>test</title>
  <script type="text/javascript">
    function sendMessage(bucketCount){
      alert(bucketCount);
    }
  </script>
</head>
<body>
</body>
</html>

And in react-native, using the webview ref, call this method:
this.webview && this.webview.injectJavaScript("sendMessage(5);");

as a result you will call the function and see your alert.
As for how to get a response from the page, you can find it in the official documentation https://github.com/react-native-community/react-na...
in a nutshell, you need to unsubscribe the onMessage method in the native native and call the window function .ReactNativeWebView.postMessage from javascript. Then, in the onMessage method, hang up a check and catch your unique key that you sent to postMessage and call the necessary functionality.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question