Search code examples
javascriptreactjsaddeventlistenerpostmessage

How to detect addEventlistener when html page is already opened via Iframe in Reactjs


I want to detect my changes in my ReactApp and want to apply those changes in Html page which is opened via Iframe.

Scenario: I want to use PostMessage handler to update my selected/changed data into my already open html page.

I tried this with "window.postMessage" and "window.AddEventlistener" but my changes are not reflecting here. What I need to change to make this work. Any suggestion?

//test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <script>
      window.addEventListener("message", receiveMessage, false);

      function receiveMessage(event)
      
      {
        if(event) {
          
          console.log(event.target.value, "hello"); // The idea is too receive the device selected 
        }
        
      }
    </script>
    
</head>
<div>
  <tr>
    Hii
  </tr>
</div>
</body>
</html>

//ReactApp page

  handleSelectDevice(type, event) {

    window.postMessage(JSON.stringify({'data': event.target.value}), "*");

  }

//IframeReactjs page

class Test extends React.Component {

  render() {
    const testUrl = process.env.PUBLIC_URL+"/test.html";
    return (
      <Iframe id="testid" src={testUrl} width="100%" height={240} />
    );
  }
}

export default Test;

Solution

  • You need to use the "window" of the iframe, not the main window object when calling postMessage().

    Considering ifr is a variable referencing the iframe element in (HTMLIFrameElement), its window is defined in ifr.contentWindow, so the call would be something like

    ifr.contentWindow.postMessage(...);
    

    More details here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

    UPDATE:
    Dummy working example here: https://codesandbox.io/s/react-example-createref-postmessage-nh881?file=/src/App.js