“iframe 里发了消息,父页面没收到。”window.postMessage 不是“发出去就一定能收”,它受 targetOrigin、窗口引用、消息格式和安全校验影响。跨窗口通信最容易犯的错,是把 targetOrigin 写成 *,又在接收端不校验来源。
父页面向 iframe 发消息:
const frame = document.querySelector('iframe').contentWindow;
frame.postMessage(
{ type: 'get-token', requestId: 1 },
'https://child.example.com'
);接收端监听:
window.addEventListener('message', (event) => {
if (event.origin !== 'https://parent.example.com') return;
if (event.source !== window.parent) return;
if (event.data?.type !== 'token') return;
console.log(event.data.value);
});targetOrigin 决定消息能发给哪些源;event.origin 是发送方源;event.source 是发送方窗口引用。三者都要校验。
*写 * 表示“不限制目标源”,任何当前窗口里的页面都能收到。如果窗口被导航到恶意站点,消息就会泄露。
正确做法是写明确的 origin,例如 https://child.example.com。targetOrigin 必须是字符串 origin(可带端口),不能传 URL 对象;写错会静默丢弃。如果子页面可能有多域名,按白名单逐个判断,不要用通配。
postMessage 是广播式的:同一窗口的多个监听器都能收到。需要一对一通道时,用 MessageChannel:
const channel = new MessageChannel();
frame.postMessage({ type: 'init' }, 'https://child.example.com', [channel.port2]);
channel.port1.onmessage = (event) => {
console.log('private', event.data);
};port2 通过第三个参数转移给子页面,之后两端用 port1/port2 直接通信,不再经过全局 message 事件。适合长期、私密的双向通道。接收端通过 event.ports[0] 拿到 port;port.start() 在 onmessage 赋值后通常自动调用,显式调用更稳。通道用完要 close(),页面卸载时关闭,避免泄漏。
postMessage 用结构化克隆算法,能传对象、数组、Map、Set、ArrayBuffer、Blob;不能传函数、DOM 节点、类实例的原型方法。event.data 要做 schema 校验:type 白名单、字段类型、长度限制;不要直接 Object.assign 到状态。
ArrayBuffer 可以转移(transfer),转移后原窗口不能再访问,能避免拷贝大块数据。SharedArrayBuffer 需要页面开启跨源隔离(COOP/COEP),否则不可用。
第一,不校验 origin。只判断 event.data.type,任何窗口都能伪造消息。
第二,不校验 source。event.origin 对了,但消息可能来自同源的其他窗口;需要 event.source === iframe.contentWindow。
第三,把 token 放在 URL。消息体里传敏感数据可以,但不要拼到 iframe src 的 query 上。
第四,接收端直接 eval 或 innerHTML。消息内容不可信,按不可信输入处理。
第五,忘记 noopener。用 window.open 打开第三方页面时,对方可以通过 window.opener 反向操作;加 noopener 切断引用。跨域 iframe 建议加 sandbox,只给必要权限;allow-same-origin 和 allow-scripts 同时给会削弱隔离。
同源窗口可以直接读 DOM、调函数;跨源窗口只能靠 postMessage。不要用 postMessage 传 DOM 节点、函数或类实例,结构化克隆会失败。消息体尽量用可序列化的普通对象,并带 type 字段做协议区分。
BroadcastChannel 适合同源多标签广播;postMessage 适合 iframe、popup 这类跨窗口通信。两者都不要传敏感数据到不可信窗口;跨源场景必须校验 origin 和 source。
iframe 加 sandbox 后,即使允许脚本,跨源 postMessage 仍可用;但 allow-same-origin 会恢复同源能力,按需开启。不要为了“方便通信”同时放开 allow-same-origin 和 allow-scripts,那等于削弱隔离。
postMessage 的核心是“明确目标源、校验来源、限制消息结构”。targetOrigin 不用 *,接收端同时校验 origin 和 source,敏感通道用 MessageChannel。把消息当不可信输入,跨窗口通信才安全;这一点要记住,别图省事,按规范来,别留缺口了。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。