Cross-domain iframe height adaptive solution

Sorry, this article is not written in English and has not been translated into English yet .You can view this article in English with Google Translate, or please come back later.

背景

大多数应用平台中会通过iframe的方式插入跨站的应用。大多数时候基本上能满足需求,但是如果遇到一些比较特殊的应用,他们的高度并不是固定的,会随着应用内容而变化。虽然会有滚动条的出现,但是这样从某种程度上会影响到页面的美观。于是乎,有没有一种方案可以让iframe的高度随着iframe内容而变化呢?

尝试

  • 通过javascript获取iframe的内容高度。设置iframe的告诉和内容高度相同。

    这种方案在同域的情况下百试不爽,但是缺点是在跨域的情况下,却无能为力。

  • 在iframe里面引入一段js,通过js实时检测iframe内容的高度,发送到服务器。嵌入iframe的页面不停的从服务器获取传过来的iframe的高度,并设置。

    这种方案,确实可以解决问题,但是却有些令人不爽的地方。

    • 不停的向服务器发送数据,增加量服务器的负担。

    • Javasript 不停的请求服务器,获取新的高度。这种不停的轮询,也确实让人蛋疼。

  • 在上面的基础上如果能避开服务器,不失为是一种好方法,但是如何才能避开服务器呢?

    我们尝试了cookie、local storage等等,希望能有一种方案可以跨过域的限制,但都以失败告终。

    最后,突然灵光一现,如果能通过一层代理作为桥梁解决跨域的问题,那么所有的问题不就会迎刃而解了么?

方案

域!我们通过上面的实验已经在iframe插入了一段js,这就意味着我们可以随意的控制iframe里面的内容了。这时候如果我们在iframe中通过js插入一个iframe地址和最外面的页面是同域的话,是不是就可以通讯了呢?于是就有了下面的模型

a.com/index.html
<body>
    <iframe src="b.com">
        content
        <script src="a.com/iframe.js" type="text/javascirpt"> </script>
        <!--通过javascript加入的iframe-->
        <iframe src="a.com/height.html"></iframe>
    </iframe>
</body>
a.com/iframe.js
    var height = document.height;
    var iframe2 = document.createElement('iframe');
    iframe2.height = 0;
    iframe2.src = "http://a.com/height.html";
    document.body.appendChild(iframe2);
a.com/height.html
<body>
    <script type="text/javascript">
         alert(top.document.getElementsByTagName('iframe')[0])
    </script>
</body>

通过上面的代码我们惊奇的发现,height.html确实可以取到a.com/index.html里面的东西。

实现

于是乎,问题就简单了,只要把iframe的高度传给index.html就ok了,改写代码如下

a.com/iframe.js

    var height = document.height;
    var iframe2 = document.createElement('iframe');
    iframe2.height = 0;
    iframe2.style.display = 'none';
    iframe2.src = "http://127.0.0.1/test3.html?height=" + document.height + '&v' + Math.random();
    document.body.appendChild(iframe2);
    setInterval(function() {
        if(document.height!=height){
            iframe2.src = "http://a.com/height.html?height=" + document.height + '&v' + Math.random();
            height=document.height;
        }
    }, 10);
a.com/height.html
<body> 
    <script type="text/javascript">
        var height=/height=(\d+)&/.exec(location.href)[1];
        top.document.getElementsByTagName('iframe')[0].height = parseInt(height);
    </script>
</body>

总结

问题解决了,满身的轻松,该方案的主要方法就是在iframe创建一个同源的iframe,通过地址传递iframe的高度,这样的话就可以打通iframe和外界的联系,实现了高度的自适应。

353550
  • logo
    • HI, THERE!I AM MOFEI

      (C) 2010-2024 Code & Design by Mofei

      Powered by Dufing (2010-2020) & Express

      IPC证:沪ICP备2022019571号-1