July,31st,2009

利用location.hash实现跨域iframe自适应高宽

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

实现效果:
A域名下的页面a.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.taobao.com/c.html,它负责读取location.hash里面的width和height的值,然后设置与它同域下的a.html中的iframe的宽度和高度.

代码如下:

a.html代码

首先a.html中通过iframe引入了b.html
<iframe id=”b_iframe” height=”0″ width=”0″ src=”http://www.alimama.com/b.html” frameborder=”no” border=”0px” marginwidth=”0″ marginheight=”0″ scrolling=”no” allowtransparency=”yes” ></iframe>

b.html代码

<iframe id=”c_iframe”  height=”0″ width=”0″  src=”http://www.taobao.com/c.html” style=”display:none” ></iframe>
<script type=”text/javascript”>
var b_width = Math.max(document.body.scrollWidth,document.body.clientWidth);
var b_height = Math.max(document.body.scrollHeight,document.body.clientHeight);
var c_iframe = document.getElementById(”c_iframe”);
c_iframe.src = c_iframe.src+”#”+b_width+”|”+b_height; //http://www.taobao.com/c.html#width|height”
}
</script>
<!–js读取b.html的宽和高,把读取到的宽和高设置到和a.html在同一个域的中间代理页面车c.html的src的hash里面–>

c.html代码

<script type=”text/javascript”>
var b_iframe = window.parent.parent.document.getElementById(”b_iframe”);
var hash_url = window.location.hash;
var hash_width = hash_url.split(”#”)[1].split(”|”)[0]+”px”;
var hash_height = hash_url.split(”#”)[1].split(”|”)[1]+”px”;
b_iframe.style.width = hash_width;
b_iframe.style.height = hash_height;
</script>
a.html中的iframe就可以自适应为b.html的宽和高了.

其他一些类似js跨域操作问题也可以按这个思路去解决

18 Responses to “利用location.hash实现跨域iframe自适应高宽”

  1. jin says:

    如果iframe里面的页面含有js改变高度,滚动条还是不可避免的出现。

  2. andyt says:

    不支持opera

  3. 换热器 says:

    这是个好东西收藏一下,晚上有空看.

  4. IT网 says:

    iframe自适应高宽可以参照这里

    http://www.ad0.cn/netfetch/read.php/218.htm

    location.hash的方式,有点繁琐,且对于包含页面有限制

  5. 乐奥商城 says:

    跨域的iframe客户端操作还是很有难度的,除非两个站都是自己做的....

  6. s13b says:

    牛妞啊

  7. 路人甲 says:

    其他跨域共享数据问题,感觉还是直接script简单些,用hash毕竟传递数据量有限,还得搞个代理页面

  8. 路人甲 says:

    貌似这里有个小问题,b.html代码,iframe都没加载,JS就操作其属性了,能获取到DOM?

  9. tjubao says:

    不错,学习了。

  10. cuikai says:

    很好的思路,感谢分享

  11. hite says:

    利用url,当iframe加载完毕的后,递归使用resize事件,可以吧。

  12. cssrain says:

    一般都是这么解决的。
    跨域的页面中,然后嵌套一个 不跨域 的页面。
    然后通过不跨域的 页面来完成一些东西。

  13. Hobosic says:

    Amazing! Not clear for me, how offen you updating your ued.alimama.com.
    Thank you
    Hobosic

  14. 乐蜂网 says:

    有技术难度。。。

  15. redthink says:

    跨域操作还可以这么想,厉害

  16. [...] 利用location.hash实现跨域iframe自适应高宽« UED.Alimama.com [...]

  17. [...] 利用location.hash实现跨域iframe自适应高宽« UED.Alimama.com [...]

Leave a Reply