How do iframes on a page communicate?
TL;DR
Frames talk through window.postMessage(message, targetOrigin), which works across origins. The sender gets a reference to the other window (iframe.contentWindow, window.parent, window.top, window.opener), posts a structured-cloneable message, and the receiver listens for the message event. Always pass an exact targetOrigin and verify event.origin on receipt. For high-volume or request/response traffic, transfer a MessageChannel port. Same-origin frames can also access each other's DOM directly or use BroadcastChannel.
Parent → iframe
// parent page, https://app.example.com
const frame = document.querySelector('iframe#widget');
frame.addEventListener('load', () => {
frame.contentWindow.postMessage(
{ type: 'init', theme: 'dark' },
'https://widget.example.net' // only deliver if the frame is still this origin
);
});
iframe → parent
// inside https://widget.example.net
const PARENT_ORIGIN = 'https://app.example.com';
window.addEventListener('message', (event) => {
if (event.origin !== PARENT_ORIGIN) return; // ignore everyone else
if (event.data?.type === 'init') applyTheme(event.data.theme);
});
window.parent.postMessage({ type: 'resize', height: document.body.scrollHeight }, PARENT_ORIGIN);
event.source is the sender's window, so you can reply with event.source.postMessage(…, event.origin).
Request/response with MessageChannel
// parent
const { port1, port2 } = new MessageChannel();
port1.onmessage = (e) => console.log('reply', e.data);
frame.contentWindow.postMessage({ type: 'connect' }, 'https://widget.example.net', [port2]);
// iframe
window.addEventListener('message', (e) => {
if (e.origin !== PARENT_ORIGIN || e.data.type !== 'connect') return;
const port = e.ports[0];
port.onmessage = (m) => port.postMessage({ ok: true, echo: m.data });
});
A dedicated port avoids filtering every message event on window and gives you a private channel after a single origin check. Libraries like Comlink or Penpal build RPC on top of this.
Security checklist
- Never use
'*'astargetOriginfor sensitive data. If the frame navigated to another site,*would leak it. - Validate
event.originwith an exact match (notincludesorendsWith('example.com'), whichevilexample.compasses). - Treat
event.dataas untrusted input. Validate its shape, neverevalit or inject it as HTML. - Use the
sandboxattribute on untrusted iframes (sandbox="allow-scripts"withoutallow-same-origingives it an opaque origin), andallow(Permissions Policy) to restrict features. - Protect your own pages from being framed with
frame-ancestorsin CSP.
Other options
| Method | When |
|---|---|
Direct DOM access (iframe.contentDocument) | Same-origin only |
BroadcastChannel('name') | Same-origin frames/tabs, pub/sub |
localStorage + storage event | Same-origin tabs (legacy pattern) |
| URL fragment changes | Old cross-origin hack, avoid |
Data is copied with the structured clone algorithm: functions and DOM nodes can't be sent, while ArrayBuffers and ports can be transferred (zero-copy).
In an interview, mention…
postMessage+messageevent, with exacttargetOriginandevent.originchecks.MessageChannelfor request/response, and RPC wrappers.- Sandboxing and treating messages as untrusted input.
References
Spotted a mistake or a rights concern? Report an issue