zoukankan      html  css  js  c++  java
  • postMessage实现跨域iframe自适应

    通常情况下实现跨域iframe通讯,一般都是利用iframe页面再嵌套父域的代理页面来实现参数的传递。下面介绍怎么用html5的postmessage来实现跨域通讯。

    postMessage是html为了解决跨域通信,特别引入的一个新的API,目前支持这个API的浏览器有:Firefox, IE8+, Opera, Safari, Chrome。postMessage允许页面中的多个iframe/window的通信,postMessage也可以实现ajax直接跨域,不通过服务器端代理。

    这里实现一个跨域iframe高度自适应demo来说明postmessage的使用

    在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之类的繁琐方法。严重推荐大家练习下该方法,目前的确存在浏览器差异问题,但相信以后会成为主流跨域通信方案。

  • 相关阅读:
    适配器模式
    注册模式
    工厂模式
    策略模式和注入控制反转
    验签
    php中加密和解密
    asp.net textbox keyup事件触发后台的textchange事件
    jquery $.post 返回json数据
    网页播放音频、视频文件——基于web的html 5的音乐播放器(转载)
    c# 柱状图(转载)
  • 原文地址:https://www.cnblogs.com/pengjv/p/3417903.html
Copyright © 2011-2022 走看看