解决location.hash跨域iframe自适应问题

猿友 2021-01-08 17:04:14 浏览数 (1779)
反馈

页面域关系:

主页面 a.html 所属域A:www.taobao.com

被 iframe 的页面 b.html 所属域B:www.alimama.com,假设地址:https://www.w3cschool.cn/

实现效果:

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=”https://www.w3cschool.cn/” 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; //https://www.w3cschool.cn/#width|height”

}

</script>

<!–js读取b.html的宽和高,把读取到的宽和高设置到和a.html在同一个域的中间代理页面车c.html的src的hash里面–>

<iframe id=”c_iframe” height=”0″ width=”0″ src=”https://www.w3cschool.cn/” 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 跨域操作问题也可以按这个思路去解决


0 人点赞