ifream 跨域实现高度自适应

情景:

  a.xx.com中有一个ifream,ifream的id为 main_ifream. ifream中嵌入页面 b.xx.com/1.html

解决方案:

  1、在b.xx.com/1.html中嵌入js,向a.xx.com发送window.message, 消息信息中包含页面b.xx.com/1.html的高度

  2、在a.xx.com中接收从b.xx.com消息的高度,设置ifream的高度。

源代码:

  1、b.xx.com中嵌入发送消息js

  

var crossDomainHeightJS = {
    CROSS_DOMAIN: "*",
    CURRENT_CALLBACK: null,
    SCROLL_TOP_VAL: 0,
    init: function() {
        setInterval(function() {
            crossDomainHeightJS.initHeight();
        }, 500);
    },
    initHeight: function() {
        try {
            var bodyHeight = document.body.scrollHeight || window.document.body.scrollHeight;
            var docHeight = document.documentElement.scrollHeight || window.document.documentElement.scrollHeight;
            var height = Math.min(bodyHeight, docHeight);
            window.parent && window.parent.postMessage && window.parent.postMessage(JSON.stringify({height: height}), crossDomainHeightJS.CROSS_DOMAIN)
        } catch (e) {
            console.log(e);
        }
    }
};
crossDomainHeightJS.init();

  2、a.xx.com中接收消息,设置ifream的高度

  

//监听事件来源
        window.addEventListener("message", function (e) {
            routEvent(e);
        }, false);
        //跨域事件路由
        var routEvent = function (event) {
            try {
                if (event) {
                    var origin = event.origin;
                    if (origin.indexOf(".xx.com") == origin.length - 7) {
                        var param = event.data;
                        var data = JSON.parse(param);
                        for (var key in data) {
                            if (key == "height") {
                                $("#main_iframe").attr("height", data[key]);
                                break;
                            }
                        }
                    }
                }
            }catch (e) {
                console.log(e)
            }
        };

说明:origin.indexOf(".xx.com") == origin.length - 7,校验是否都是来自xx.com的消息。如果两个页面不是相同域名,是否可以去掉?暂时没有尝试,后面可以试一下

  

posted @ 2018-02-23 15:23  liuwt365  阅读(309)  评论(0编辑  收藏  举报