I'm trying to load a react url as an iframe in my jsp project.
Here my sender side code block:
<iframe id="eda"
style="display: none;"
src="http://myhost:3000/"
width="100%" height="600" border="0" marginwidth="0"
marginheight="0" scrolling="no">
</iframe>
****
function loadReactIframe(){
document.getElementById("eda").contentWindow.postMessage('GET MESSAGE FROM ME', '*');
}
I also tried the following:
function loadReactIframe(){
document.getElementById("eda").contentWindow.postMessage(
'GET MESSAGE FROM ME',
'http://myhost', 3000
);
}
My recevier (react) code block:
componentDidMount() {
window.addEventListener('load', this.handleLoad);
alert('componentDidMount')
}
handleLoad(event) {
alert(event.data);
}
But i can not get the data from event.
Listener/ReceiverThe receiver window should set up a listener/handler to the message event. The e argument (event) passed to the listener function has the data property which contains the string/object dispatched by postMessage() .
Create a function called webviewRef and attach it to the WebView component. Next, create a function called sendDataToWebView and add the code below to it. Inside the “script” tag, use window. addEventListener to listen to the event from the React Native app.
postMessage method allows different windows or iframes to communicate directly, even if they were loaded from different origins, circumventing the usual same-origin policy. The sender of the message can restrict the origin of the receiver by specifying a target origin.
There is already a useful hook made for this. https://www.npmjs.com/package/@rottitime/react-hook-message-event
Readme page has the instructions but here is a idea of how it works Install the hook:
npm i @rottitime/react-hook-message-event
In your component use it as you would with any other hook such e.g. useState
.
Import the file in your component
import {useMessage} from '@rottitime/react-hook-message-event'
You can listen to a message and use a callback to respond. For example take the following scenario:
hello
from child windowhello
from childworld
to child//listens for the 'hello' message from window.postMessage()
useMessage('hello', (send, payload) => {
//use sendMessage to post back to the sender
send({ type: 'world', success: true });
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With