Reference

postMessage rules

Short rules. Words match CONTEXT.md.

How you get a handle

You want You write
Window inside an iframe element iframe.contentWindow
Page that embeds this page window.parent
Outermost page window.top
Page that opened this popup window.opener
New window you just opened the return value of window.open

If you are not in an iframe, parent and top are this window. A popup is not in an iframe. On a popup, parent is the popup. noopener means open returns null.

What you hold

You write You hold Same origin Different origin
iframe.contentWindow WindowProxy of the child You can read the document You can use postMessage
window.parent / top WindowProxy of the parent You can read the document You can use postMessage
window.open / opener WindowProxy of the popup You can read the document You can use postMessage

If the origins are different, you can use postMessage, focus, blur, and close. You can read closed, frames, opener, parent, top. MDN.

Two fields

targetOrigin

You set this when you send. The receiver origin must match. If it does not match, the browser discards the data. There is no error. "/" means your origin. "*" means any origin.

event.origin

You read this when you receive. It is the origin of the sender. If you do not check it, any holder of your WindowProxy can send data to you.

event.source

You read this when you receive. It is the WindowProxy of the sender. Reply on it. Pass event.origin as targetOrigin. Compare it to iframe.contentWindow to find the element.

What the browser does

  1. The browser makes a structured clone of the data. A bad value throws now.
  2. If targetOrigin is not * and the receiver origin does not match, the browser returns. There is no event.
  3. The browser queues a task. Your current code finishes first.
  4. The browser fires message with data, origin, and source.

Source: HTML — window post message steps.

Defaults

Who can hear

Not this API