window.postMessage是html5中新增了一個新的跨域方法,可以用它向其他window對象發送消息,即使不同源也是可以發送消息。
兼容性:目前IE8+、FireFox、Chrome、Opera等瀏覽器都支持
postMessage的參數
參數 | 描述 |
---|---|
data | 是傳遞過來的message |
source | 發送消息的窗口對象 |
origin | 發送消息窗口的源(協議+主機+端口號) |
1.向iframe中傳遞數據
當前頁面
<script>
function load() {
var iframe = document.getElementById('iframe');
//確保你使用的是iframe的contentWindow屬性,而不是節點對象
var win = iframe.contentWindow;
//這裏允許跨域地址我們不作限定,你可以自己定義
win.postMessage('我是本地頁面傳遞的文字','*');
}
</script>
<iframe
id="iframe"
src="https://bannerl.github.io/html/domain/domain.html"
onload="load()">
</iframe>
目標頁面
window.onmessage = function(e){
e = e || event;
var content = document.getElementById('content');
content.innerHTML = e.data;
}
2.新窗口傳遞數據
必須window.open打開的新窗口才能通信,在新窗口打開的時候,我們需要指定打開頁面的window.name
。
當前窗口 (a頁面)
<button id="button">點我我更換傳遞信息</button>
<script>
var host = 'http://localhost:8089';
var newPageUrl = 'http://localhost:8089/b.html';
var newPage = window.open(newPageUrl,"newPage");
var message = '我是a頁面傳遞的數據';
//由於新頁面加載完畢後,才能接收消息,所以這裏用定時器發送消息,等到消息成功發送後關閉定時器
var timer = setInterval(function(){
newPage.postMessage(message,host);
},200);
//更新數據
var btn = document.getElementById('button');
btn.onclick = function() {
message = '我是a頁面傳遞的數據'+(new Date()).getTime();
newPage.postMessage(message,host);
}
//監聽消息反饋
window.addEventListener('message',function(event) {
if(event.data === "success"){
clearInterval(timer);
}
},false);
</script>
新窗口 (b頁面)
window.onmessage = function(e) {
e = e || event;
if(event.origin !== 'http://localhost:8089') return;
alert(e.data);
//執行成功反饋消息
event.source.postMessage('success',event.origin);
}