iframe获取子页面高度(跨域)解决方案
需求:A域名下 index2.html 使用iframe嵌套 B域名下 index2.html ,通过B域名下页面高度,来控制A域名下iframe的高度。 简单说就是:跨域条件下,A页面使用iframe嵌套B页面,通过B页面的高度,来控制A页面iframe的高度。
图中描述很形象,一共需要创建3个页面,来实现此功能;
操作:
为了区分域名,A域名下为A.com B域名为B.com
1.创建A域名下index2.html页面 ,即创建iframe,引入B域名下访问地址
HTML:
<div>
<iframe id="test12" src="https://B.com/test2/index2.html" width="100%" height="200px" frameborder="no" border="0" marginwidth="0" marginheight="0" ></iframe>
</div>
2.创建B域名下index2,html页面 , 需要引入A域名下index3.html(引入一个div,方便显示高度,iframe不设置高度了。)
HTML:
<div style="height:500px;">
</div>
<iframe id="iframe" src="https://A.com/test2/index3.html" width="0" height="0"></iframe>
JS:
function sethash(){
//判断浏览器兼容性
var explorer = window.navigator.userAgent ;
if(explorer.indexOf("Chrome") >= 0){
hashH = document.documentElement.scrollHeight; //获取自身高度
}else{
hashH=document.body.scrollHeight;
}
urlC = "https://A.com/test1/index3.html"; //设置iframeA的src
document.getElementById("iframe").src=urlC+"?height="+hashH; //将高度作为参数传递
}
window.onload=sethash;
3.创建A域名下index3.html,根据B域名传递高度,设置A域名下index2.html下iframe高度(同域名下,可设置)
JS:
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null)
return unescape(r[2]);
return null;
}
function pseth() {
var iObj = window.parent.parent.document.getElementById('iframe');//A和main同域,所以可以访问节点
window.parent.parent.document.getElementById("test12").setAttribute("height", getQueryString("height") + "px");
}
pseth();
总结:
iframe跨域的问题,实际是A嵌套B嵌套C,B传递给C,AC为同一域名下,可以进行操作。将C获取到B传递的值,赋值给A作为iframe的高度。
资料参数:https://www.iteye.com/blog/imalex163-2183338
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· Qt个人项目总结 —— MySQL数据库查询与断言