一般狀況下實現跨域iframe通信,通常都是利用iframe頁面再嵌套父域的代理頁面來實現參數的傳遞。下面介紹怎麼用html5的postmessage來實現跨域通信。html
postMessage是html爲了解決跨域通訊,特別引入的一個新的API,目前支持這個API的瀏覽器有:Firefox, IE8+, Opera, Safari, Chrome。postMessage容許頁面中的多個iframe/window的通訊,postMessage也能夠實現ajax直接跨域,不經過服務器端代理。html5
這裏實現一個跨域iframe高度自適應demo來講明postmessage的使用ajax
在www.a.com域的index.html頁面嵌入www.b.com的content.html頁面跨域
<div style="border-top: 1px #ccc solid; margin: 10px 0px;" id="J_ContentWrap"> <iframe src="http://www.b.com/content.html" id="J_Content" width="100%" scrolling="no" frameborder="0"></iframe> </div>
同時,在index頁面監聽postmessage消息瀏覽器
var iObj = document.getElementById('J_Content'); //消息處理函數 var onmessage = function(e){ var data = e.data; //提取參數 var height = /%([0-9]+)%/.exec(data)[1]; if(height == 0){ parent.parent.document.getElementById("J_ContentWrap").style.display = "none"; } else{ iObj.height = height; } } //監聽postMessage消息事件 if (typeof window.addEventListener != 'undefined') { window.addEventListener('message', onmessage, false); } else if (typeof window.attachEvent != 'undefined') { window.attachEvent('onmessage', onmessage); }
在www.b.com的content.html頁面中獲取頁面自己實際高度,利用postmessage傳遞參數給父頁面。 postMessage這個函數接收二個參數,缺一不可,第一個參數即你要發送的數據,第二個參數是很是重要,主要是出於安全的考慮,通常填寫容許通訊的域名。安全
function sethash(height){ var iframeH; if(height != null || height != undefined){ iframeH = height; } else{ iframeH = $(document.body).outerHeight(true); } var message = "參數%" + iframeH + "%" + (new Date().getTime()); //向父頁面傳遞參數 window.parent.postMessage(message, 'http://www.a.com'); } window.onload = function(){ sethash(); };
至此,postmessage跨域iframe自適應方案已經完成。你們能夠看到postMessage至關強悍和易用!你能夠利用這個特性解決大部分場景下的跨域問題,不用再建立個代理iframe之類的繁瑣方法。嚴重推薦你們練習下該方法,目前的確存在瀏覽器差別問題,但相信之後會成爲主流跨域通訊方案。服務器