窗口間的通信用的地方還是挺多的,比如彈出qq登錄認證窗订框。先上兼容性
兼容性
基本用法其實也比較簡單培愁。
window.open方法會返回一個窗口對象,使用這個對象可以向子窗口發(fā)送消息绎谦,而子窗口可以通過window.opener向父窗口發(fā)送消息,先新建兩個html
index.html(只展示body粥脚,其他地方省略了)
<body>
<button onclick="opwin()">打開</button>
<script type="text/javascript">
function opwin() {
//保留窗口對象
var popup = window.open("test.html", "_blank");
}
function receiveMessage(event) {
//event.origin是指發(fā)送的消息源窃肠,一定要進行驗證!K⒃省冤留!
if (event.origin !== "http://localhost")return;
//event.data是發(fā)送過來的消息碧囊。
console.log(event.data);
//event.source是指子窗口,主動向子窗口發(fā)送消息可以用popup
//postMessage有兩個參數(shù)纤怒,消息和自己的源(例如http://www.baidu.com)糯而,自己的源應該和目標源相同。否則發(fā)送會失敗泊窘。
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指的就是父窗口(打開本窗口的窗口)
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是通過網(wǎng)絡協(xié)議烘豹,所以不能以直接在瀏覽器打開html的方式進行調(diào)試瓜贾。而是應該放在服務器上,走網(wǎng)絡協(xié)議
比如携悯,這樣是不對的
錯誤
這樣才行
正確