App下載

解決location.hash跨域iframe自適應(yīng)問題

猿友 2021-01-08 17:04:14 瀏覽數(shù) (2322)
反饋

頁面域關(guān)系:

主頁面 a.html 所屬域A:www.taobao.com

被 iframe 的頁面 b.html 所屬域B:www.alimama.com,假設(shè)地址:http://www.o2fo.com/

實(shí)現(xiàn)效果:

A域名下的頁面 a.html 中通過 iframe 嵌入B域名下的頁面 b.html,由于 b.html 的寬度和高度是不可預(yù)知而且會(huì)變化的,所以需要 a.html中的iframe 自適應(yīng)大小.

問題本質(zhì):

js 對跨域 iframe 訪問問題,因?yàn)橐刂?a.html 中 iframe 的高度和寬度就必須首先讀取得到 b.html 的大小,A、B不屬于同一個(gè)域,瀏覽器為了安全性考慮,使js跨域訪問受限,讀取不到 b.html 的高度和寬度.

解決方案:

引入代理代理頁面 c.html 與 a.html 所屬相同域 A,c.html 是A域下提供好的中間代理頁面,假設(shè) c.html 的地址:www.taobao.com/c.html,它負(fù)責(zé)讀取 location.hash 里面的 width 和 height 的值,然后設(shè)置與它同域下的 a.html 中的 iframe 的寬度和高度.

代碼如下:

a.html 代碼

首先 a.html 中通過 iframe 引入了 b.html

<iframe id=”b_iframe” height=”0″ width=”0″ src=”http://www.o2fo.com/” frameborder=”no” border=”0px” marginwidth=”0″ marginheight=”0″ scrolling=”no” allowtransparency=”yes” >

</iframe>

b.html代碼

<script type=”text/javascript”>

var b_width = Math.max(document.documentElement.clientWidth,document.body.clientWidth);

var b_height = Math.max(document.documentElement.clientHeight,document.body.clientHeight);

var c_iframe = document.getElementById(”c_iframe”); //liehuo.net

c_iframe.src = c_iframe.src+”#”+b_width+”|”+b_height; //http://www.o2fo.com/#width|height”

}

</script>

<!–js讀取b.html的寬和高,把讀取到的寬和高設(shè)置到和a.html在同一個(gè)域的中間代理頁面車c.html的src的hash里面–>

<iframe id=”c_iframe” height=”0″ width=”0″ src=”http://www.o2fo.com/” style=”display:none” ></iframe>

c.html代碼

<script type=”text/javascript”>

var b_iframe = 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 就可以自適應(yīng)為 b.html 的寬和高了.
其他一些類似 js 跨域操作問題也可以按這個(gè)思路去解決


0 人點(diǎn)贊