Two-way communication between a parent window and an iframe is a pretty common need in web development. The MessageChannel API makes it easy to set this up by creating two connected ports (port1 and port2). This small project is an example on how to set up both ports in react parents and iframes GitHub Repository
The Idea
- Parent Frame: Creates a MessageChannel and stores port1 in a ref, listens for the iframe's load event, and sends port2 to the iframe using postMessage from the Channel Messaging API.
- Iframe: Sets up a listener for the message event, stores port2 in a ref, and uses it for two-way communication with the parent.
To Do
- Store both port1 and port2 in useContext hook, so they will be available on the entire application.