Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get postmessage data from react?

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.

like image 832
lesstalkmorecode Avatar asked Mar 29 '19 06:03

lesstalkmorecode


People also ask

How do I get Windows postMessage?

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() .

How do I get data from react native in WebView?

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.

What is Targetorigin postMessage?

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.


1 Answers

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:

  1. Parent window listens for the message hello from child window
  2. Parent receives hello from child
  3. Parent sends back world 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 });
});
like image 79
rottitime Avatar answered Sep 17 '22 13:09

rottitime