2级域名跨域情况下Iframe高度自适应

javascript

2009-10-16 16:23

www.123.com/a.html 框架iframe嵌入 000.123.com/b.html



页面域关系


主页面a.html所属域A:www.123.com/a.html
被iframe的页面b.html所属域B:000.123.com,假设地址:http://000.123.com/b.html

实现效果

A域下的页面1.html中通过iframe嵌入B域下的页面b.html,由于b.html的宽度和高度是不可预知而且会变化的,所以需要a.html中的iframe自适应大小.

问题本质:

js对跨域iframe访问问题,因为要控制a.html中iframe的高度和宽度就必须首先读取得到b.html的大小,A、B不属于同一个域,浏览器为了安全性考虑,使js跨域访问受限,读取不到b.html的高度和宽度.

解决方案:

引入代理代理页面c.html与a.html所属相同域A,c.html是A域下提供好的中间代理页面,假设c.html的地址:www.123.com/c.html,它负责读取location.hash里面的width和height的值,然后设置与它同域下的a.html中的iframe的宽度和高度.

A代码---------------------------------------------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>主页面</title></head>
<body>

<div style="border:1px solid #ccc;padding:10px;">
<iframe id="frame_content" name="frame_content" src="http://000.123.com/b.html" width="100%" height="0" scrolling="no" frameborder="0"></iframe>
</div>
</body>
</html>

B代码---------------------------------------------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>被iframe嵌套页面</title></head>
<body>

<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1
<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1
<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1


<iframe id="iframeC" name="iframeC" src="" width="0" height="0" style="display:none;" ></iframe>

<script type="text/javascript">
function sethash(){
    hashH = document.documentElement.scrollHeight;
    urlC = "http://www.123.com/c.html";
    document.getElementById("iframeC").src=urlC+"#"+hashH;
}
window.onload=sethash;
</script>

</body>
</html>

C代码---------------------------------------------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>中介页面</title></head>

<body>

<script>
function pseth() {
    var iObj = parent.parent.document.getElementById('frame_content');
    iObjH = parent.parent.frames["frame_content"].frames["iframeC"].location.hash;
    iObj.style.height = iObjH.split("#")[1]+"px";
}
pseth();
</script>

</body>
</html>