页面通信的方式 :postMessage向指定窗口发送信息
是 HTML5 引入的一个跨文档通信 API,允许不同窗口或 iframe 之间安全地发送消息。通过,你可以向指定的窗口或 iframe 发送信息,并且接收方可以通过监听message事件来接收这些信息。
postMessage 是 HTML5 引入的一个跨文档通信 API,允许不同窗口或 iframe 之间安全地发送消息。通过 postMessage,你可以向指定的窗口或 iframe 发送信息,并且接收方可以通过监听 message 事件来接收这些信息。
使用方法
发送消息
targetWindow.postMessage(message, targetOrigin, [transfer]);
-
targetWindow: 目标窗口的引用,通常是通过window.open()、iframe.contentWindow或window.parent获取的。 -
message: 要发送的消息,可以是任何 JavaScript 对象(通常是字符串、数字、对象等)。 -
targetOrigin: 目标窗口的源(协议 + 主机 + 端口),用于确保消息只发送给指定的源。可以使用"*"表示不限制源,但不推荐。 -
transfer(可选): 一个可选的 Transferable 对象数组,用于传递所有权。
接收消息
在接收方窗口中,通过监听 message 事件来接收消息:
window.addEventListener('message', function(event) {
// 检查消息的来源是否可信
if (event.origin !== 'http://example.com') return;
// 处理接收到的消息
console.log('Received message:', event.data);
});
-
event.origin: 发送消息的窗口的源。 -
event.data: 发送的消息内容。 -
event.source: 发送消息的窗口的引用,可以用来回复消息。
示例
发送消息的窗口
// 假设我们有一个 iframe
var iframe = document.getElementById('myIframe');
// 获取 iframe 的 contentWindow
var targetWindow = iframe.contentWindow;
// 向 iframe 发送消息
targetWindow.postMessage('Hello from parent!', 'http://example.com');
接收消息的窗口(iframe 内部)
// 监听 message 事件
window.addEventListener('message', function(event) {
// 检查消息的来源是否可信
if (event.origin !== 'http://example.com') return;
// 处理接收到的消息
console.log('Received message:', event.data);
});
注意事项
-
安全性: 始终检查
event.origin以确保消息来自可信的源,避免跨站脚本攻击(XSS)。 -
跨域问题:
postMessage可以用于跨域通信,但需要确保目标窗口的源是正确的。 -
消息格式: 消息可以是任何 JavaScript 对象,但通常建议使用字符串或 JSON 格式,以便在不同浏览器之间兼容。
1. 通过 window.open() 打开的窗口
如果你使用 window.open() 打开了一个新窗口,可以通过返回值获取目标窗口的引用:
// 打开一个新窗口
var targetWindow = window.open('http://example.com', '_blank');
// 向新窗口发送消息
targetWindow.postMessage('Hello from opener!', 'http://example.com');
2. 通过 iframe 的 contentWindow
如果你有一个嵌入的 iframe,可以通过 iframe.contentWindow 获取目标窗口的引用:
// 获取 iframe 元素
var iframe = document.getElementById('myIframe');
// 获取 iframe 的 contentWindow
var targetWindow = iframe.contentWindow;
// 向 iframe 发送消息
targetWindow.postMessage('Hello from parent!', 'http://example.com');
3. 通过 window.parent 获取父窗口
如果你在一个 iframe 中,可以通过 window.parent 获取父窗口的引用:
// 在 iframe 中向父窗口发送消息
window.parent.postMessage('Hello from iframe!', 'http://example.com');
4. 通过 window.opener 获取打开当前窗口的窗口
如果当前窗口是由另一个窗口通过 window.open() 打开的,可以通过 window.opener 获取打开者的窗口引用:
// 在打开的窗口中向打开者发送消息
window.opener.postMessage('Hello from opened window!', 'http://example.com');
5. 通过 window.frames 获取子窗口
如果你有多个嵌套的 iframe,可以通过 window.frames 获取子窗口的引用:
// 获取第一个 iframe 的窗口引用
var targetWindow = window.frames[0];
// 向子窗口发送消息
targetWindow.postMessage('Hello from parent!', 'http://example.com');
6. 通过 window.top 获取顶层窗口
如果你在一个嵌套的 iframe 中,可以通过 window.top 获取顶层窗口的引用:
// 在 iframe 中向顶层窗口发送消息
window.top.postMessage('Hello from nested iframe!', 'http://example.com');
更多推荐


所有评论(0)