window.onmessage not working in react js component

Viewed 1019

I have to load react js app in iframe and parent application is sending data to iframe react app using below code:

  const myiframe = document.getElementById('myIframe');
  myiframe.contentWindow.postMessage('message', '*');


  <iframe id='myIframe' name="my-iframe" src="http://localhost:3000" ></iframe>

In iframe app I am trying to receive data:

useEffect(() => {
    window.onmessage = function (event) {
      console.log('event received')
    }
  }, []);

But window.onmessage never triggers or triggers intermittently.

I checked by keeping window.onmessage out of useEffect but it is not working.

Has anyone faced this issue? Need help.

Thanks.

1 Answers

This is simple code, not important what is in your iframe and what is in your parent app, we need just a share a function on a global variable like window

in you parent app just call :

window.callMe('Hello world');
or
window.callMe({status:true, message:'hello world'});

and in your iframe (react in your sample) just define callMe on parent window :

myFunc=(data)=>{
    console.log(data);
}
window.parent.callMe = myFunc;

sample code:

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const callIframeFunc = () => {
    window.callMe("Hello");
  };
  return (
    <div className="App">
      <h1>React rel with iframe Demo</h1>
      <iframe
        id="unqiframe"
        title="a"
        srcDoc="<div><script>function myFunc(data){document.getElementsByClassName('testp')[0].innerHTML = 'received data : '+data} window.parent.callMe = myFunc;</script><p class='testp'>No data</p></div>"
        allow="autoplay"
      ></iframe>
      <div>
        <button onClick={callIframeFunc}>Call iFrame Func</button>
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

DEMO

Related