简体   繁体   中英

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.

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 eg 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 });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM