欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > Window.postMessage() —— 主窗口和 iframe弹框怎么通信?

Window.postMessage() —— 主窗口和 iframe弹框怎么通信?

2025/7/4 17:08:52 来源:https://blog.csdn.net/Pandora_417/article/details/144589763  浏览:    关键词:Window.postMessage() —— 主窗口和 iframe弹框怎么通信?

postMessage()Window 接口中的一个方法,用于在不同的浏览上下文之间发送消息,比如在主窗口和 iframe、弹窗之间,或者与 Web Worker 通信。它是实现 跨域通信 的核心机制之一,能够在安全的前提下进行不同源之间的交互。

语法

targetWindow.postMessage(message, targetOrigin, [transfer]);
// 1、message (必填): 要发送的数据,可以是字符串、对象等。
// 2、targetOrigin (必填): 指定消息接收者的源,确保安全通信。格式为 协议 + 域名 + 端口;设置为 "*",消息会发送给任意域名,但不建议。
// 3、transfer (可选):传递的可转移对象(如 ArrayBuffer、MessagePort)。传递后,原对象在发送方将不可用,适合处理大数据。

用法示例

1. 主窗口与 iframe 通信

主窗口:

const iframe = document.querySelector('iframe');// 向 iframe 发送消息
iframe.contentWindow.postMessage({ type: 'greeting', text: 'Hello iframe!' }, 'https://example.com');

iframe 内:

event.origin 信息来源
event.data 接受到的数据
event.source 当前窗口对象
window.addEventListener('message', (event) => {// 验证消息来源if (event.origin !== 'https://example.com') return;console.log('收到消息:',event, event.data);// 回信event.source.postMessage( "hi there yourself!  the secret response " + "is: rheeeeet!",event.origin,);
});

注意事项

  1. 安全性:
    • 始终设置具体的 targetOrigin,不要使用 "*",避免潜在的安全风险。
    • 在接收消息时,验证 event.origin 是否可信。
  2. 浏览器支持:
    • postMessage() 是现代浏览器的标准功能,支持几乎所有主流浏览器。
  3. 跨域限制:
    • 虽然 postMessage 可以实现跨域通信,但需要双方脚本都正确处理消息。

应用场景

  • 跨域通信:实现不同源之间的数据传递。
  • iframe 通信:主窗口与嵌入的 iframe 进行数据交互。
  • Web Worker:主线程与 Worker 线程之间的消息传递。
  • 弹窗通信:主窗口与弹窗之间的交互。
  • 微前端:在不同微前端子应用之间共享数据。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词