關於postMessage
window.postMessage雖說是html5的功能,可是支持IE8+,假如你的網站不須要支持IE6和IE7,那麼能夠使用window.postMessage。關於window.postMessage,不少朋友說他能夠支持跨域,不錯,window.postMessage是客戶端和客戶端直接的數據傳遞,既能夠跨域傳遞,也能夠同域傳遞。html
應用場景
我只是簡單的舉一個應用場景,固然,這個功能不少地方能夠使用。html5
假如你有一個頁面,頁面中拿到部分用戶信息,點擊進入另一個頁面,另外的頁面默認是取不到用戶信息的,你能夠經過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延遲再發用。dom
接受的頁面
//監聽消息反饋 window.addEventListener('message',function(event) { if(event.origin !== 'http://haorooms.com') return; //這個判斷一下是否是我這個域名跳轉過來的 console.log('received response: ',event.data); },false);
以下圖,接受頁面獲得數據post
若是是使用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);
上面的代碼片斷是往消息源反饋信息,確認消息已經收到。下面是幾個比較重要的事件屬性:spa
source – 消息源,消息的發送窗口/iframe。code
origin – 消息源的URI(可能包含協議、域名和端口),用來驗證數據源。htm
data – 發送方發送給接收方的數據。