Today we’re going to see how we can communicate a web created with React with an iFrame or frame in React or HTML with JavaScript.
Loading the Frame
We create an iframe:
<iframe src={urlCargar} style={{ width: '100%', height: '500px' }} />
In urlCargar we put the URL of the web from which we want to capture the event.
Now we create the event that will allow us to obtain the data:
useEffect(() => { function handleReceiveMessage(event: MessageEvent) { // Check if the origin of the message is the expected one if (event.origin !== "http://localhost:3000" && event.origin !== "your_url") { // Do not handle the message if the origin is unknown return; } // If it's not JSON (we receive plain text): // alert(receivedData); // If a JSON object is received: const receivedData = JSON.parse(event.data); alert(JSON.stringify(receivedData)); } window.addEventListener('message', handleReceiveMessage); return () => { window.removeEventListener('message', handleReceiveMessage); }; }, []);
First we check that we are receiving from the correct URL:
if (event.origin !== "http://localhost:3000" && event.origin !== "your_url") { // Do not handle the message if the origin is unknown return; }
*You must indicate in your_url the URL where you expect to receive the events.
And now, to obtain the event, if it is text or an object it is done as follows:
// If it's not JSON (we receive plain text): // alert(receivedData); // If a JSON object is received: const receivedData = JSON.parse(event.data); alert(JSON.stringify(receivedData));
React
In React we are going to create a web for example test.tsx
First we have to define a new type for Window (which React Native WebView asks us for)
declare global { interface Window { ReactNativeWebView: any; } }
And now simply where we want to communicate the event we can:
window.ReactNativeWebView.postMessage("Hello");
Or we can even send JSON objects:
window.parent.postMessage(JSON.stringify(objToSend));