Explain Codes LogoExplain Codes Logo

Html5 - Cross Browser iframe postMessage - child to parent?

html
postmessage
cross-browser
event-listener
Nikita BarsukovbyNikita Barsukov·Feb 22, 2025
TLDR

To perform a child-to-parent communication in an iframe, postMessage is at your service. Apply this in the child iframe.

// yeah, like sending signals to the mother-ship parent.postMessage('Hey there!', 'https://parent-domain.com');

Now, set up a secure message listening post within the parent.

window.addEventListener('message', (event) => { if (event.origin === 'https://iframe-domain.com') { // parent checking for their legitimate child ;-) console.log('Hey, my child said:', event.data); } });

Use your actual site URLs in place of domain origins. This approach offers a guaranteed safe and cross-browser friendly communication.

Secure communication best practices

Always validate origin

Make sure to cross-verify event.origin in your message event handler. This is crucial for security.

if (event.origin !== 'https://trusted-source.com') { // A Spidey sense to detect foreign entities return; }

Event listener cleanup

Cleaning up event listeners in React is essential to prevent memory leaks when components dismount:

useEffect(() => { const messageHandler = (event) => { /* ... handle messages ... */ }; window.addEventListener('message', messageHandler); return () => { // Time for some spring cleaning window.removeEventListener('message', messageHandler); }; }, []);

Complex app state management

Complex apps demand advanced state management. Consider Redux to handle state changes prompted by iframe messages.

PostMessage and browser compatibility

Fish out postMessage support

Check this resource to understand cross-browser compatibility. Discontinuing support for older browsers might be crucial for safety and simplicity.

Broad browser event listener compatibility

Where broader compatibility is required, especially with Internet Explorer 8 or earlier, adopting a suitable method to add event listeners (addEventListener v/s attachEvent) is important.

function addEvent(element, event, handler) { if (element.addEventListener) { // modern folks, step right in element.addEventListener(event, handler, false); } else if (element.attachEvent) { // Welcome to the Jurassic Park, IE8 users! element.attachEvent('on' + event, handler); } } addEvent(window, 'message', messageHandler);

Pitfalls and how to dodge them

Avoid "*" as targetOrigin

'*' in postMessage(targetOrigin) may pose an attractive, but dangerous shortcut. For safety, prefer defining the exact target origin.

Validate the message source

For extra security, along with event.origin, also cross-verify event.source against the expected iframe.

Throttling message handling

If your app expects a high volume of postMessage, consider debouncing or throttling the message handler for better performance.

let timeout; // ready for the onslaught window.addEventListener('message', (event) => { clearTimeout(timeout); // Out with the old timeout = setTimeout(() => { // In with the new // Handle the message here... }, 200); });

Useful resources and bonus tips

Learn from the wise

Consider exploring libraries that create abstractions over postMessage in frameworks like React. They offer established patterns and make your implementation easier.

Read the manual

Always refer to the postMessage documentation on MDN Web Docs for the most detailed, reliable information.

Data safety first

For JSON data exchange, ensure you serialize with JSON.stringify and parse with JSON.parse. This prevents unintended data manipulation or JavaScript injections — play safe!