postMessage()
这是H5引入的一个API,可以实现跨文档、多窗口、跨域消息的传递。
otherWindow.postMessage(message,targetOrigin,[transfer])
otherWindow其它窗口的一个引用,比如iframe的contentWindow属性, 执行window.open返回的窗口对象,或者是命名过或数值索引的window.iframestargetOrigin通过窗口的origin属性来指定哪些窗口能接收到消息事件,其值可以是字符串"*",表示无限制,如果是/则表示同源transfer(可选) 是一串和message同时传递的Transferable对象,这些对象的所有权将转移给消息的接收方,而发送发不再保有所有权
message(接收信息)
data从其它window中传递过来的数据对象orgin接收到的信息来自于哪个窗口
用途
-
页面和其打开的新窗口的数据传递
-
多窗口之间消息传递
-
页面与嵌套的 iframe 消息传递
具体代码实现
//源窗口
<body>
<button id="btn">open</button>
<button id="send">send</button>
<!-- 通过 iframe 嵌入子页面(接收消息目标窗口) -->
<iframe src="http://try/a.html"
id="otherWin"></iframe>
<script>
window.onload = function() {
var win;
//通过window.open打开接收消息目标窗口
win = window.open('http://try/a.html', 'popUp');
}
// 方法一: 通过 postMessage 向子窗口发送数据
win.postMessage('Hello', 'http://try/');
// 方法二: 通过 postMessage 向子窗口发送数据
document.getElementById("otherWin").contentWindow
.postMessage(
document.getElementById("message").value,
"http://try/");
};
</script>
</body>
//目标窗口b.html
<script>
window.onload = function() {
var text = document.getElementById('txt');
//监听函数,接收一个参数--Event事件对象
function receiveMsg(e) {
if(e.origin === "http://try/" { //验证源窗口
console.log(e.data)
}
}
if (window.addEventListener) { //其它浏览器
//为window注册message事件并绑定监听函数
window.addEventListener('message', receiveMsg, false);
}else { //IE浏览器
window.attachEvent('message', receiveMsg);
}
};
</script>
注意
为了安全起见,在接受消息时要验证消息是否来自你预期的源窗口