Iframe跨域自适应高度(兼容IE/Firefox)终极解决方案
main.html在A域,被包含的iframe.html、proxy.html以及proxy.js在B域
main.html
<script type="text/javascript" src="http://zhaohe162.blog.163.com/blog/B域/proxy.js"></script>
<script type="text/javascript">
var aai=new AutoAdjustIframe();
aai.autoAdjust('frameName');
</script>
<div style="border:1px solid #ccc;padding:10px;">
<iframe id="frameName" name="frameName" src="http://zhaohe162.blog.163.com/blog/B域 /iframe.html?hostname=192.168.1.100:8080" style="width:100%;border:1px solid #f00;" scrolling="no" frameborder="0"></iframe>
</div>
<br/>尾部<br/>
iframe.html
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
文字<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<script type="text/javascript" src="http://zhaohe162.blog.163.com/blog/proxy.js"></script>
<script type="text/javascript">
var aai=new AutoAdjustIframe();
aai.setHash();
</script>
proxy.html
B域一个空白页面,防止404
proxy.js
var AutoAdjustIframe=function(){
var autoSecond=1;
this.autoAdjust=function(iframeId){
setInterval(function(){
try{
var height=parseFloat(window.frames[iframeId].frames[iframeId+'-proxyiframe'].location.hash.replace(/^#/,''))||100;
document.getElementById(iframeId).style.height=height+'px';
}catch(e){};
},autoSecond);
};
var getHeight=function(){
return Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,
document.documentElement.clientHeight,document.body.clientHeight);
};
/*
* 设置代理页的hash值,需要A域传给B域hostname
*/
this.setHash=function(){
var aSearch=document.location.search.match(/hostname=([^&]+)/);
if(!!aSearch){
//设定 代理页面url
var proxyUrl='http://'+aSearch[1]+'/proxy.html';
var height=getHeight();
try{
console.log('proxyUrl:'+proxyUrl+' The Iframe's height:'+height);
}catch(e){};
//生成代理iframe
var iframe=document.createElement('iframe');
iframe.src=proxyUrl+'#'+height;
iframe.id=window.name+'-proxyiframe';
iframe.name=window.name+'-proxyiframe';
iframe.style.display='none';
document.body.appendChild(iframe);
//动态设置代理iframe的hash,以便重新获取新的高度
var interval=setInterval(function(){
if(getHeight()!=height){
height=getHeight();
iframe.src=proxyUrl+'#'+height;
try{
console.log('Reloading,The Iframe's height:'+height);
}catch(e){};
}
},autoSecond);
}
};
};