0

Here is the situation I am rendering a class component in which an iframe referring to html file is present and want to send message to my main component that is rendered from iframe but it seems to not work here is what I have tried.... class component

class DemoComponent extends React.Component {
componentDidMount() {
  window.addEventListener("message", (event) => {
    console.log("Message from iframe:", event.data);
  });
}
  render() {
    return (
      <iframe
        src="path/to/your/iframe.html"
      ></iframe>
    );
  }
}

iframe.html

<script>
  window.addEventListener("DOMContentLoaded", function () {
    console.log("Message from iframe");
    window.parent.postMessage("Message from iframe", "*");
  });
window.parent.console.log("from html")
window.top.console.log("from html")
</script>

I tried this code

<iframe
        src="path/to/your/iframe.html"
        onLoad={(e) => {
          e.target.contentWindow.postMessage("Ready", "*");
        }}
      ></iframe>

from here postMessage API works correct, I am able to get the message

But I really wanted it to happen through html file I am also trying to log comment from html file that is put inside of iframe, so that I see them on the browser console when I render the class component but it does not seem to work

There is no Content Security Policy Setup Or please let me know if are other ways to hold communication between an html file and a react component

here is link with same issue window.postMessage not working from iframe to parent document but I am not able to get it to work for onload of the component and I am relatively new please let me know on my mistakes

Mo_Ra
  • 1
  • 1

0 Answers0