Reading time: 2 minutes
Today I’m going to show you how you can communicate a web page with React Native directly using JavaScript and a webview.
The first thing you need to do is install the webview dependency in React Native:
npm install react-native-webview
Now let’s create two components: one will be the React Native component that loads the URL and waits for communication, and the other will be the HTML component that sends data to the React Native component.
WebView.js
import React, { useState } from "react"; import { View, StyleSheet, Text, Dimensions } from "react-native"; import { WebView } from 'react-native-webview'; var urlCargar = "https://www.....com/test_click.html" const MapClickView = ({ navigation, route }) => { const { } = route.params; return () }; export default MapClickView; const styles = StyleSheet.create({ texto: { fontSize: 30, color: '#000', }, contenedorInicio: { flex: 1, alignContent: 'center', alignItems: 'center', }, webview: { width: Dimensions.get('window').width, height: Dimensions.get('window').height, flex: 1, }, contenedorBarra: { flex: 1, width: '100%', }, contenedor: { flex: 10, width: '100%', height: '100%', backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, }); function onMessage(data) { alert(data.nativeEvent.data); }
In this code, we import and create a WebView component. We also add the attribute mixedContentMode=”compatibility” to allow mixed content. Additionally, we add a callback function onMessage={onMessage} to communicate with the JavaScript in the HTML.
The data will be obtained in the function:
function onMessage(data) { alert(data.nativeEvent.data); }
Now let’s create the HTML component that will send the data:
<!DOCTYPE html> <html> <body> <button onclick="sendMessage()">Send Message</button> <script> function sendMessage() { const message = 'Hello from HTML'; window.ReactNativeWebView.postMessage(message); } </script> </body> </html>
In this HTML code, we have a button that triggers the function sendMessage()
. This function sends a message to the React Native component using window.ReactNativeWebView.postMessage()
.