MessageChannel

Lesson 6 · ~8 minutes · iframe and a Worker

The worker talks to someone else

The implicit port is parent↔worker. A minted pair is how the worker talks to a third context.

Lesson 4 kept an extra port on the parent. Lesson 5 gave both ends to two iframes. This is the mixed case in #24: mint, move port1 into an iframe, move port2 into a dedicated worker. Those twins talk. Parent is not on that pipe. The implicit port is still there for creator↔worker traffic — a different pair. (HTML §10.1.2.6, §9.4.1.2)

const { port1, port2 } = new MessageChannel();
iframe.contentWindow.postMessage("init", origin, [port1]);
worker.postMessage("init", [port2]);
worker.postMessage("job");              // implicit — still parent↔worker

The iframe hop still takes targetOrigin. The worker hop does not: the second argument is the transfer list. This lab uses "*" on the iframe hop because the frame is srcdoc in a local file, and a classic blob: Worker so file:// does not need a second file URL.

A SharedWorker is the other platform-minted port: worker.port on the page, onconnect with event.ports[0] (same object as event.source) inside. That first tab↔SharedWorker stream is already a MessagePort. Do not mint a pair for it. Mint only if that shared worker needs a second pipe, the same rule as a dedicated worker. (HTML §10.2.1)

Feel the two pipes

Transfer both minted ends. Send from the iframe — the worker echoes on that pipe. Ping implicit: parent hears the worker; the iframe does not. Then post on the original handles.

The lab needs JavaScript in this page.

Check

Parent moves port1 into an iframe and port2 into a dedicated worker. Who talks on that minted pipe?

After that extra transfer, worker.postMessage("job") talks on which pipe?

Both minted ends have moved. Parent posts on the original port1. What happens?

A tab connects to a SharedWorker and needs one stream with it. What do you use?

The worker must talk to an iframe, not to its creator. What do you use?

Which of those two hops still takes targetOrigin?

Primary source

Read the extra-pipe pattern in HTML Living Standard §10.1.2.6 (source.postMessage(message, [messageChannel.port2]) — here the other end is an iframe, not the caller). Then SharedWorker’s platform-minted port in §10.2.1 (worker.port / onconnect).

Ask the teacher

If “why isn’t the iframe just using the worker’s implicit port?” is still mushy — ask. Next: lesson 7 — close the extra pipe; the worker stays. Pocket cards: entangled ports, port API, transfer, choose.