Lesson 0003 · ~10 minutes
One skill: when a
message
arrives, reply on
event.source
with
event.origin
as
targetOrigin.
You can say this: “I do not look up the iframe to reply. I use
event.source. I pass event.origin. If
I have two iframes, I compare
event.source === iframe.contentWindow.”
A page has two widgets.
Each widget is an iframe.
Both send data to you.
You must reply to the sender.
You must not reply to the other widget.
You already know how to get a handle.
The event already holds the handle of the sender.
A window message has both of these:
event.origin
— a string. The origin of the sender at the time of the send.
event.source
— a
WindowProxy.
The handle of the sender.
(MDN)
They are not the same kind of value.
On a later lesson, event.source can also be a
MessagePort. This lesson is the window case.
window.addEventListener("message", (event) => {
if (event.origin !== "https://widget.example") return;
event.source.postMessage({ type: "ack" }, event.origin);
});
event.source picks the window.
event.origin is the
targetOrigin for that send.
(MDN)
That origin is the sender at send time. If the window goes to a new origin before the reply arrives, the browser discards the reply. There is no error. That is the same rule as lesson 1.
useEffect(() => {
function onMessage(event) {
if (event.origin !== "https://widget.example") return;
event.source.postMessage({ type: "ack" }, event.origin);
}
window.addEventListener("message", onMessage);
return () => window.removeEventListener("message", onMessage);
}, []);
You compare the handle to
contentWindow.
(MDN)
if (event.source === alphaRef.current.contentWindow) {
// the alpha iframe sent this
}
Do not use event.origin to pick the element. Two
iframes can have the same origin.
On this lesson file, both children stamp
event.origin as the text null. A string
check cannot tell them apart. The handle check can.
The box below has two real iframes: Alpha and Beta.
source===alpha.contentWindow true.
source===beta.contentWindow true.
Do the five steps first. Then answer these questions.
You receive a message. You need to reply to the sender.
Two iframes sent. You need the iframe element.
A message arrives. What are event.origin and event.source?
You reply with targetOrigin set to event.origin.
On this file page both event.origin values match.
event.source is a WindowProxy.
event.origin is a string.
event.source.postMessage(reply, event.origin).
event.source === iframe.contentWindow.
MDN — The dispatched event. Then mapping message sources to iframes.