How to send messages from React Native code to the page loaded into WebView and back.
Despite pretty good online documentation for React Native WebView component, it might be pretty hard to find a working example of sending messages to the WebView from React Native code and back.
This tutorial is based on react-native-webview
module version 8.0.4 and expo
2.14.0 which corresponds to react-native
0.53.0.
Full example code is available on GitHub
Sending messages from React Native code ⟶ to the page loaded into WebView.
Use WebView.injectJavaScript
method to execute JavaScript code in context of the WebView:
const injected = `
document.getElementById("counter").innerHTML='${value}';
`;
webView.current.injectJavaScript(injected);
Injected javascript code has full access to DOM and to the global JavaScript window
variable.
Sending messages from JavaScript code running in WebView ⟶ to React Native.
You need to use ReactNativeWebView.postMessage(...);
function in your JavaScript code running inside the WebView in order to send the messages to React Native code.
ReactNativeWebView.postMessage
supports the only string parameter which should be your serialized message.
Use onMessage
WebView event listener in your React Native code to handle those messages:
<WebView
...
onMessage={(event) => {
const { data } = event.nativeEvent;
console.log('String message from the WebView', data);
}}
/>
P.S. Apparently react-native-community
Github repository contains a very detailed documentation page explaining WebView usage in details.