How can i get postmessage data from react?

11,153

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 });
});
Share:
11,153
lesstalkmorecode
Author by

lesstalkmorecode

Updated on December 10, 2022

Comments

  • lesstalkmorecode
    lesstalkmorecode over 1 year

    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.