温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2022-02-24 17:30:14 来源:亿速云 阅读:165 作者:iii 栏目:开发技术

本篇内容主要讲解“如何解决location.hash跨域iframe自适应问题”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何解决location.hash跨域iframe自适应问题”吧!

页面域关系:

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

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

实现效果:

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.yisu.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.netc_iframe.src = c_iframe.src+”#”+b_width+”|”+b_height; //https://www.yisu.com/#width|height”}</script><!–js读取b.html的宽和高,把读取到的宽和高设置到和a.html在同一个域的中间代理页面车c.html的src的hash里面–><iframe id=”c_iframe” height=”0″ width=”0″ src=”https://www.yisu.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 就可以自适应为 b.html 的宽和高了.
其他一些类似 js 跨域操作问题也可以按这个思路去解决

到此,相信大家对“如何解决location.hash跨域iframe自适应问题”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI