前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iframe 与 postMessage 方法

iframe 与 postMessage 方法

原创
作者头像
挥刀北上
修改2023-06-20 17:00:08
5200
修改2023-06-20 17:00:08
举报
文章被收录于专栏:Node.js开发Node.js开发

iframe 与 postMessage 方法

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

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

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

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

代码语言:javascript
复制
// 拿到 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:

代码语言:javascript
复制
window.addEventListener('message', handleMessage, false);

// 或者
window.onmessage = handleMessage

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

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

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

代码语言:javascript
复制
// 在 iframe 中发送消息
window.parent.postMessage('Hello to parent from iframe!', 'http://www.example.com');

参考

1. Iframes and the postMessage Method

2. Window.postMessage() MDN

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • iframe 与 postMessage 方法
    • 例:父级页面向 iframe 页面发消息
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档