How do iframes communicate with the parent page?

JavaScript

The short answer

Iframes communicate with the parent page using the postMessage API. The parent sends messages to the iframe with iframe.contentWindow.postMessage(), and the iframe sends messages to the parent with window.parent.postMessage(). Both sides listen for messages using the message event. This works even across different origins.

Parent to iframe

// Parent page
const iframe = document.querySelector('iframe');
iframe.contentWindow.postMessage(
{ type: 'UPDATE', data: { user: 'John' } },
'https://child-domain.com' // target origin for security
);
// Inside the iframe
window.addEventListener('message', (event) => {
// Always verify the origin
if (event.origin !== 'https://parent-domain.com') return;
console.log(event.data); // { type: "UPDATE", data: { user: "John" } }
});

Iframe to parent

// Inside the iframe
window.parent.postMessage(
{ type: 'RESIZE', height: document.body.scrollHeight },
'https://parent-domain.com'
);
// Parent page
window.addEventListener('message', (event) => {
if (event.origin !== 'https://child-domain.com') return;
if (event.data.type === 'RESIZE') {
document.querySelector('iframe').style.height =
event.data.height + 'px';
}
});

Security

Always verify event.origin before processing messages. Without this check, any page could send messages to your window:

window.addEventListener('message', (event) => {
// Always check the origin
if (event.origin !== 'https://trusted-domain.com') return;
// Now safe to process the message
handleMessage(event.data);
});

Also specify the target origin when sending (not '*'), so the message is only delivered to the intended recipient.

Same-origin iframes

If the iframe is on the same origin, you can access its DOM directly:

// Parent accessing iframe content (same origin only)
const iframeDoc = iframe.contentDocument;
const heading = iframeDoc.querySelector('h1');

This does not work cross-origin — the browser blocks it due to the same-origin policy.

Interview Tip

Show the postMessage pattern for both directions (parent to iframe and iframe to parent). The security check on event.origin is the most important part — always mention it. This shows you think about security, not just functionality.

Why interviewers ask this

This comes up when building embedded widgets, payment forms, or third-party integrations. Interviewers want to see if you know the postMessage API and understand the security implications of cross-origin communication.