跨域 iframe 通信必须使用 window.postMessage(),发送方调用 iframe.contentWindow.postMessage(),接收方监听 message 事件并严格校验 event.origin 和 event.source;document.domain 已基本淘汰;服务端代理或同源中转页可作为补充方案。
跨域 iframe 通信不能直接访问 contentWindow 或 contentDocument,强行读写会触发 SecurityError: Blocked a frame from accessing a cross-origin frame。必须走标准的、受控的跨源消息机制。
window.postMessage() 发送和监听消息是最通用且安全的方式这是唯一被所有现代浏览器支持的原生跨域 iframe 通信方案。发送方调用 iframe.contentWindow.postMessage(),接收方在目标窗口中监听 message 事件。
targetOrigin(如 "https://example.com"),不能用 "*"(除非你完全信任所有可能的源)event.origin 和 event.source,防止伪造消息undefined 等)contentWindow 可能为 null,需监听 load 事件后再发iframe.addEventListener('load', () => {
iframe.contentWindow.postMessage({ type: 'INIT', data: 'hello' },
'https://remote-site.com');
});
window.addEventListener('message', (e) => {
if (e.origin !== 'https://remote-site.com') return;
if (e.source !== iframe.contentWindow) return;
console.log('Received:', e.data);
});
document.domain 只适用于同主域不同子域(已基本淘汰)仅当两个页面同属一个一级域名(如 a.example.com 和 b.example.com),且都显式设置 document.domain = 'example.com' 时,才能解除同源限制。但该方法:
http vs https)、端口不同、或完全无关域名document.domain 对跨域 iframe 的影响(部分场景仍保留,但不可依赖)postMessage
当无法控制 iframe 源站(比如嵌入第三方广告/支付 SDK),又需要更深度交互时,可在自己域名下部署一个中转页(如 /proxy.html),由它加载目标 iframe 并通过 postMessage 桥接通信。
postMessage 回传真正麻烦的不是发不出消息,而是收不到回执、消息丢失、或 origin 校验漏掉导致 XSS 风险。每次 postMessage 都该配对设计响应逻辑,并始终检查 event.origin —— 这一点比语法正确更重要。