postMessage实现跨域iframe自适应

一般状况下实现跨域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之类的繁琐方法。严重推荐你们练习下该方法,目前的确存在浏览器差别问题,但相信之后会成为主流跨域通讯方案。服务器

相关文章
相关标签/搜索