蝙蝠岛资源网 Design By www.hbtsch.com
复制代码 代码如下:
<body onload="javascript: setHeight();">
<script>
function setHeight(){
var dHeight = document.documentElement.scrollHeight;
var t = document.createElement("div");
t.innerHTML = '<iframe id="kxiframeagent" src="/UploadFiles/2021-04-02/agent.html#'+dHeight+'">document.documentElement.appendChild(t.firstChild);
}
</script>

我想着跨域如何解决啊!后来去网上搜索了一下子 恍然大悟

具体如下 我是复制过来了 大家重点理解一下子它的实现思路 :


问题:

A域名下的页面a.htm中通过iframe嵌入B域名下的页面b.html,由于b.html的大小等是不可预知而且会变化的,所以需要 a.htm中的iframe自适应大小.

问题本质 :

js的跨域问题,因为要控制a.htm中iframe的大小就必须首先读取得到b.html的大小,A、B不属于同一个域,js的访问受限,读取不 到b.html的大小.

解决方案:

首先前提是A,B是合作关系,b.html中能引入A提供的js

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

复制代码 代码如下:
<iframe id="aIframe" height="0" width="0" src="/UploadFiles/2021-04-02/b.html"><iframe id="aIframe" height="0" width="0" src="http://www.b.com/html/b.html">
B在b.html中引入了A提供的js文件

Html代码
复制代码 代码如下:
<script language="javascript" type="text/javascript" src="/UploadFiles/2021-04-02/a.js">
该js首先读取b.html的宽和高,然后创建一个iframe,src为和A同一个域的中间代理页面a_proxy.html,吧读取到的宽和 高设置到src的hash里面

Html代码
复制代码 代码如下:
<iframe id="iframeProxy" height="0" width="0" src="/UploadFiles/2021-04-02/a_proxy.html#width|height">
a_proxy.html是A域下提供好的中间代理页面,它负责读取location.hash里面的width和height的值,然后设置与 它同域下的a.html中的iframe的宽和高.

Js代码
复制代码 代码如下:
var pParentFrame = parent.parent.document.getElementById("aIframe");
var locationUrlHash = parent.parent.frames["aIframe"].frames["iframeProxy"].location.hash;
pParentFrame.style.width = locationUrlHash.split("#")[1].split("|")[0]+"px";
pParentFrame.style.height = locationUrlHash.split("#")[1].split("|")[1]+"px";
var pParentFrame = parent.parent.document.getElementById("aIframe");
var locationUrlHash = parent.parent.frames["aIframe"].frames["iframeProxy"].location.hash;
pParentFrame.style.width = locationUrlHash.split("#")[1].split("|")[0]+"px";
pParentFrame.style.height = locationUrlHash.split("#")[1].split("|")[1]+"px";

这样的话a.html中的iframe就自适应为b.html的宽和高了.

其他一些类似js跨域操作问题也可以按这个思路去解决
标签:
跨域,iframe,自适应大小

蝙蝠岛资源网 Design By www.hbtsch.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
蝙蝠岛资源网 Design By www.hbtsch.com

评论“js跨域问题之跨域iframe自适应大小实现代码”

暂无js跨域问题之跨域iframe自适应大小实现代码的评论...

稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!

昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。

这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。

而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?