iframe 与 postMessage 方法

iframe 与 postMessage 方法

postMessage 用于跨文档通信,如父页面向内嵌的 iframe 发消息。

既是发消息,就有发送方与接收方,发送方要调用 postMessage 方法,接收方要注册 onmessage 事件处理函数,处理接收的消息。

例:父级页面向 iframe 页面发消息

发送方:拿到 iframe 页面的引用然后调用postMessage 方法:

// 拿到 iframe 中的 window 对象
var wn = document.getElementById('ifrm').contentWindow;
// postMessage 参数: 1.要发送的数据, 2.目标域名
wn.postMessage('Hello to iframe from parent!', 'http://www.example.com');

接收方:注册 message event handler:

window.addEventListener('message', handleMessage, false);

// 或者
window.onmessage = handleMessage

message event handler 会被传入一个事件对象,包含以下属性:

  • data: 发送过来的消息数据
  • origin: 发送方的站点信息(含protocol、hostname、port)
  • source: 发送方的 window 对象引用
// 接收方的 message event handler
function handleMessage(event) {
    // MDN 建议在处理消息前要先检查发送方的域名,防止恶意消息
    if (event.origin === 'http://www.example.com') {
        // 处理消息
        ...
        // 发送回执给发送方
        event.source.postMessage('Message received', event.origin);
    }
}

子页面向父页面发送消息同理:

// 在 iframe 中发送消息
window.parent.postMessage('Hello to parent from iframe!', 'http://www.example.com');

参考

1. Iframes and the postMessage Method

2. Window.postMessage() MDN

posted @   RockyMountain  阅读(13489)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示