利用location.hash實現跨域iframe自適應

來源:互聯網
上載者:User

頁面域關係:

首頁面a.html所屬域A:www.jb51.net
被iframe的頁面b.html所屬域B:www.baidu.com,假設地址:http://www.baidu.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.jb51.net/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.baidu.com/b.html” 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”);
c_iframe.src = c_iframe.src+”#”+b_width+”|”+b_height; //http://www.jb51.net/c.html#width|height”
}
</script>

<!–js讀取b.html的寬和高,把讀取到的寬和高設定到和a.html在同一個域的中間代理頁面車c.html的src的hash裡面–>
<iframe id=”c_iframe” height=”0″ width=”0″ src=”http://www.jb51.net/c.html” 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就可以自適應為b.html的寬和高了.

其他一些類似js跨網域作業問題也可以按這個思路去解決

如果不是跨域訪問,可以參考這篇文章。iframe自適應高度的多種方法方法小結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.