窗口間的通信用的地方還是挺多的,比如彈出qq登錄認(rèn)證窗。先上兼容性

兼容性
基本用法其實(shí)也比較簡(jiǎn)單。
window.open方法會(huì)返回一個(gè)窗口對(duì)象,使用這個(gè)對(duì)象可以向子窗口發(fā)送消息,而子窗口可以通過(guò)window.opener向父窗口發(fā)送消息,先新建兩個(gè)html
index.html(只展示body,其他地方省略了)
<body>
<button onclick="opwin()">打開(kāi)</button>
<script type="text/javascript">
function opwin() {
//保留窗口對(duì)象
var popup = window.open("test.html", "_blank");
}
function receiveMessage(event) {
//event.origin是指發(fā)送的消息源,一定要進(jìn)行驗(yàn)證?。?!
if (event.origin !== "http://localhost")return;
//event.data是發(fā)送過(guò)來(lái)的消息。
console.log(event.data);
//event.source是指子窗口,主動(dòng)向子窗口發(fā)送消息可以用popup
//postMessage有兩個(gè)參數(shù),消息和自己的源(例如http://www.baidu.com),自己的源應(yīng)該和目標(biāo)源相同。否則發(fā)送會(huì)失敗。
event.source.postMessage("我是主窗口,我接收到消息了",window.location);
}
//添加消息接收函數(shù)
window.addEventListener("message", receiveMessage, false);
</script>
</body>
test.html
<body>
<button onclick="send()">發(fā)送</button>
<script type="text/javascript">
function send() {
//window.opener指的就是父窗口(打開(kāi)本窗口的窗口)
window.opener.postMessage("我是子窗口,向主窗口發(fā)送消息", window.location);
}
function receiveMessage(event) {
if (event.origin !== "http://localhost")return;
console.log(event.data);
}
window.addEventListener("message", receiveMessage, false);
</script>
</body>
由于postMessage是通過(guò)網(wǎng)絡(luò)協(xié)議,所以不能以直接在瀏覽器打開(kāi)html的方式進(jìn)行調(diào)試。而是應(yīng)該放在服務(wù)器上,走網(wǎng)絡(luò)協(xié)議
比如,這樣是不對(duì)的

錯(cuò)誤
這樣才行

正確