Lesson 0006 · ~10 minutes
One skill: pick the window or a MessagePort by who must hear the data.
You can say this: “A window send can reach every listener on that window. A port send reaches only who holds the port. I still use the window to give the port.”
A page has two iframes. Alpha and Beta.
Both add a listener on the window.
A send to Alpha’s
contentWindow
does not go to Beta. You already know that.
A send to both windows reaches both listeners.
If you later add a third listener on Alpha’s window, that listener
also hears Alpha’s window traffic. You filter with
event.origin.
A MessagePort is different. Only the holder of that port hears it. (HTML §9.4.1.2)
| Who must hear | What you use |
|---|---|
| A function in this same page | Call the function. Do not use postMessage. |
| Many tabs with the same origin | BroadcastChannel. See that topic. |
| One widget. Ready, then a few messages |
Window postMessage. Check
event.origin.
|
| One widget. Other widgets must not hear | Transfer a port after ready. Talk on the port. |
| Give the child the first port |
Window postMessage with a transfer list.
|
The first port still travels on the window. After that, the private talk is on the port.
After you transfer port2, this page cannot use that
end. On a port message, event.origin is empty. Those
are
lesson 5 facts B and D.
// trusted widget: give a port after ready
function givePort() {
const channel = new MessageChannel();
channel.port1.onmessage = onPrivate;
trustedRef.current.contentWindow.postMessage(
{ type: "port" },
"https://widget.example",
[channel.port2],
);
}
// both widgets may hear a public flag
function sendFlag(flag) {
const data = { type: "flag", flag };
trustedRef.current.contentWindow.postMessage(
data,
"https://widget.example",
);
otherRef.current.contentWindow.postMessage(
data,
"https://other.example",
);
}
event.origin. Any holder of the WindowProxy can
inject.
(MDN)
targetOrigin: "*" with a secret. Whoever
lives in the window now can read it.
postMessage on a port you already
transferred or closed.
event.data as server truth. It is a
structured clone from another page.
Alpha and Beta both listen on the window. Only Alpha will get a port.
true.port: must say held. Beta
port: must stay none.
window: lines must change.
port: must change.
Do the five steps first. Then answer these questions.
Two widgets. Only Alpha may see filter updates.
This page and the widget live in the same window.
Three same-origin tabs need the same flag.
You need to give the child the first port.
A window listener has no origin check.
HTML §9.4.1.2 — Ports as a capability. Who holds the port can talk. Then MDN Channel Messaging API.