HTML5中window.postMessage,在兩個頁面之間的數據傳遞
關於postMessage
window.postMessage雖然說是html5的功能,但是支持IE8+,假如你的網站不需要支持IE6和IE7,那么可以使用window.postMessage。關於window.postMessage,很多朋友說他可以支持跨域,不錯,window.postMessage是客戶端和客戶端直接的數據傳遞,既可以跨域傳遞,也可以同域傳遞。
應用場景
我只是簡單的舉一個應用場景,當然,這個功能很多地方可以使用。
假如你有一個頁面,頁面中拿到部分用戶信息,點擊進入另外一個頁面,另外的頁面默認是取不到用戶信息的,你可以通過window.postMessage把部分用戶信息傳到這個頁面中。(當然,你要考慮安全性等方面。)
代碼舉例
發送信息:
//彈出一個新窗口 var domain = 'http://haorooms.com'; var myPopup = window.open(domain + '/windowPostMessageListener.html','myWindow'); //周期性的發送消息 setTimeout(function(){ //var message = '當前時間是 ' + (new Date().getTime()); var message = {name:"站點",sex:"男"}; //你在這里也可以傳遞一些數據,obj等 console.log('傳遞的數據是 ' + message); myPopup.postMessage(message,domain); },1000);
要延遲一下,我們一般用計時器setTimeout延遲再發用。
接受的頁面
//監聽消息反饋 window.addEventListener('message',function(event) { if(event.origin !== 'http://haorooms.com') return; //這個判斷一下是不是我這個域名跳轉過來的 console.log('received response: ',event.data); },false);
如下圖,接受頁面得到數據

如果是使用iframe,代碼應該這樣寫:
//捕獲iframe var domain = 'http://haorooms.com'; var iframe = document.getElementById('myIFrame').contentWindow; //發送消息 setTimeout(function(){ //var message = '當前時間是 ' + (new Date().getTime()); var message = {name:"站點",sex:"男"}; //你在這里也可以傳遞一些數據,obj等 console.log('傳遞的數據是: ' + message); //send the message and target URI iframe.postMessage(message,domain); },1000);
接受數據
//響應事件 window.addEventListener('message',function(event) { if(event.origin !== 'http://haorooms.com') return; console.log('message received: ' + event.data,event); event.source.postMessage('holla back youngin!',event.origin); },false);
上面的代碼片段是往消息源反饋信息,確認消息已經收到。下面是幾個比較重要的事件屬性:
source – 消息源,消息的發送窗口/iframe。
origin – 消息源的URI(可能包含協議、域名和端口),用來驗證數據源。
data – 發送方發送給接收方的數據。
