showing results for - "how to communicate with an iframe react"
Clemence
25 Jan 2021
1const Render = () => {
2  useEffect(() => {
3    const handler = event => {
4      const data = JSON.parse(event.data)
5      console.log("Hello World?", data)
6    }
7
8    window.addEventListener("message", handler)
9
10    // clean up
11    return () => window.removeEventListener("message", handler)
12  }, []) // empty array => run only once
13
14  return (
15    <div>
16      <iframe
17        srcDoc={`
18        <!DOCTYPE html>
19        <html>
20          <head>
21            window.top.postMessage(
22              JSON.stringify({
23                error: false,
24                message: "Hello World"
25              }),
26              '*'
27            );
28          </head>
29          <body>
30            <h1>Content inside an iframe, who knew...</h1>
31          </body>
32        </html>
33      `}
34      />
35    </div>
36  )
37}