Lesson 0006 · ~10 minutes

Who can hear

One skill: pick the window or a MessagePort by who must hear the data.

Win for this lesson

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.”

1. Two listeners

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)

2. Pick by who must hear

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.

React, same rule
// 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",
  );
}

3. Stop here if

4. Do these steps

Alpha and Beta both listen on the window. Only Alpha will get a port.

  1. Wait until both ready chips are true.
  2. Click Transfer port to Alpha. Alpha port: must say held. Beta port: must stay none.
  3. Click Send on window. Both window: lines must change.
  4. Click Send on Alpha port. Only Alpha port: must change.
  5. Read Beta again. Beta did not hear the port send.

5. Practice

Do the five steps first. Then answer these questions.

Question A

Two widgets. Only Alpha may see filter updates.

Question B

This page and the widget live in the same window.

Question C

Three same-origin tabs need the same flag.

Question D

You need to give the child the first port.

Question E

A window listener has no origin check.

6. Remember

Ask your teacher If a sentence is not clear, ask. If a lab step does not match the text, ask. That is part of the method.

Primary source (read next)

HTML §9.4.1.2 — Ports as a capability. Who holds the port can talk. Then MDN Channel Messaging API.