Iframe跨域JavaScript自动适应高度

重点分析:

主域名页面:页面A,页面C

其它域名页面:页面B

步骤:

1、页面A(主域名)通过Iframe()嵌套页面B(其它域名)

2、页面B(其它域名)获取自身高度值pageB_height,再通过Iframe()嵌套页面C同时传自身高度值pageB_height给页面C

3、因为页面C和页面A同域名,所以可以在页面C中获取页面A的Iframe(),并将页面A中的iframeB的高度值设为pageB_height

中间页面C(主域名):http://www.main.com/setheight.aspx

<html><head><title>JavaScript使跨域Iframe自动适应高度中间页面</title>
<script type="text/javascript">
    function pseth() {
        var iObj = window.parent.parent.document.getElementById('iframeB'); //A和main同域,所以可以访问节点
        var iObjH = "";
        try {
            iObjH = window.parent.parent.frames["iframeB"].frames["iframeA"].location.hash; //访问自己的location对象获取hash值
        } catch (e) {
            iObjH = window.location.toString();
        }

        var arr = iObjH.split("#")[1];
        var arrPasearr = arr.split("|");
        // alert(arrPasearr[0]); 
        iObj.style.height = arrPasearr[0] + "px"; //操作dom

        if (arrPasearr[1] != undefined && arrPasearr[1] != "")
            window.parent.parent.document.title = decodeURI(arrPasearr[1]) + '-吉运商城';
    }
    try {
        pseth();
    } catch (e) {
    }
</script>
</head><body></body></html>

 //code by:博客园-曹永思 

主页面A(主域名):http://www.main.com/index.aspx

<html><head><title>主页面</title>
</head><body>
<iframe ></iframe>
</body></html>

  

嵌套的页面B(其它域名): http://b.main.com/index.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head> 
    <title>嵌套在Iframe里的页面</title> 
</head>
<body bgcolor="#f1e7de">
<iframe  ></iframe>
</body> 
<script type="text/javascript">    
    function sethash() {
        var hashH = document.documentElement.scrollHeight; //获取自身高度
        var urlC = "http://www.main.com/setheight.aspx"; //设置iframeA的src
        document.getElementById("iframeA").src = urlC + "#" + hashH + "|"; //将高度作为参数传递
    }
    window.onload = sethash; 
</script>    
</html>