In a React Native WebView, you can use the postMessage method to send messages from the WebView’s JavaScript code to your React Native application. This allows for communication between the WebView and the React Native app.
To send information from webview to react native, you can call postMessage method from webview and it will fire onMessage event in react native application. So that you can easily get any information from webview.
Let’s implement an example with a local html file, we will display one simple button in the webview and on click of that button we will call the post api and send a success response to react native application.
<!DOCTYPE html> <html> <body> <h2>POST API DEMO</h2> <p id="demo"></p> <button onclick="myFunction()">Call API</button> <script> function myFunction() { var xhr = new XMLHttpRequest(); xhr.open('POST', 'https://reqres.in/api/users', true); xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8', ); xhr.onreadystatechange = function () { if (xhr.status == 201) { // calling post message function on success response window.postMessage(xhr.responseText); document.getElementById('demo').innerHTML = 'Success : ' + xhr.responseText; } }; xhr.send('name=morpheus&job=leader'); } </script> </body> </html>
I have added above html file at below locations,
Android: android/app/src/main/assets/webPage.html
Ios : ios/webPage.html
import React from 'react'; import {Platform} from 'react-native'; import {WebView} from 'react-native-webview'; const htmlPath = Platform.OS === 'android' ? 'file:///android_asset/webPage.html' : 'webPage.html'; function WebViewComp(): JSX.Element { /* assign function to postmessage window.ReactNativeWebView.postMessage will give event to onMessage */ const injectedJavascript = `(function() { window.postMessage = function(data) { window.ReactNativeWebView.postMessage(data); }; })()`; return (console.log(event?.nativeEvent?.data)} injectedJavaScript={injectedJavascript} originWhitelist={['*']} /> ); } export default WebViewComp;
You will get the output in terminal like this,