跨域引入iframe 自适应高度

时间:2023-03-08 20:45:27
跨域引入iframe  自适应高度

最近和别的公司合作一个项目,需要从他们那边引入一个页面,刚开始想的挺简单的,用iframe 引入就好啦,可是操作中才发现,自适应的问题不好解决,试了挺多办法,最终找到一个比较好的方法,记录一下,留着备用,也希望能帮助到需要的人。

一、先定义下名称:

原页面:target.html

放置iframe 的页面:index.html

二、原理:使用了html5 的message() 方法

三、如何使用:

1、target.html  页面中加入如下代码:

window.onload = function() {
    var height = document.body.scrollHeight;
    if (height <= 0 || height == undefined) {
      height = $(document).height();
    }
    parent.postMessage(height, 'https://www.baidu.com/');
  };
说明:https://www.baidu.com/   这个地址是 index.html 中的域的地址。。。。。。
2、index.html 页面中加入如下代码:
<iframe src="http://cd.edai.com/evaluateapi/" id="frm1" onload="resizeCrossDomainIframe('frm1', 'http://i.firefoxchina.cn/');" style="width:100%; " frameborder="0">
</iframe>
说明:http://i.firefoxchina.cn/   这个地址是  target.html   中的域的地址。。。。。。
<script>
        function resizeCrossDomainIframe(id, other_domain) {
            var iframe = document.getElementById(id);
            window.addEventListener('message', function(event) {
console.log(event);
                if (event.origin !== other_domain) return;
                if (isNaN(event.data)) return;
                var height = parseInt(event.data) + 32;
                iframe.height = height + "px";
            }, false);
        }
</script>
另外:相当于我在target.html 中传出来一个height的参数,在index.html 页面来接收这个参数,并执行。。当然,你也可以传其他的参数值,获取到并操作。
Message中一般常用的属性:

1、data 包含传入的消息,一般以会将传递的数据转化为字符串;

2、origin 返回消息来自的域,可以根据它来判断是否要处理消息,是非常基本的层级上的策略控制。