iframe 自适应高度

最近做到这样的项目,自己实现了一下

场景是 跨域 子页面动态高度的

自己的实现用到了 postMessage 和 跨域 代理 iframe  。

参考了这篇博客的内容,记录一下,有空再完善一下具体方案。 

 每半秒钟检测一下子页面高度,是否有变化,如果变化发送信息到主域。

it.e.addEventListener(window,'load',function(){
        
    it.winHeight = it.getHeight();
    try{postMsg('setHeight|'+it.winHeight);}catch(e){};    
    setInterval(function(){
            try{
                if(it.winHeight != it.getHeight()){
                    it.winHeight = it.getHeight();
                    postMsg('setHeight|'+it.winHeight);
                    }else{
                        //console.log(it.winHeight)    
                        }
                }catch(e){};
            },5E2);
            
        

        }); 

 postMsg 的实现:

 支持postMessage 的 调用postMessage 不支持的IE6 IE7 用iframe代理,通过调取主域下的js_proxy.html+search值 传输信息到主域。 

function postMsg(msg) { 
  if(window.parent.postMessage) { 
     window.parent.postMessage(msg, hostDomain); 
  } else {
     // alert(msg);
    var proxy = hostDomain+'/js_proxy.html?',
        frame = document.getElementById('js_proxy');
    var clear = function(f){
            try{
                f.contentWindow.document.write('');
                f.contentWindow.close();
                document.body.removeChild(frame);
            }catch(e){}
        }; 
    if(frame){
        clear(frame);
        };             
    frame = document.createElement('iframe');
        document.body.appendChild(frame);
        frame.id = "js_proxy"
        frame.style.display = 'none';
    frame.name = msg;
    frame.contentWindow.location = proxy+msg;
  }; 

 }; 

接收数据和执行的实现:

 主域中的脚本,接收message

if(window.postMessage) { 
  if(typeof window.addEventListener != 'undefined') { 
    window.addEventListener('message', onmessage, false); 
  } 
  else if(typeof window.attachEvent != 'undefined') { 
    window.attachEvent('onmessage', onmessage); 
  } 

};

主域下的js_porxy.html?msg  通过分析 location.search 来接收数据并处理。

 var hash = window.location.search.toString().substring(1);

        //alert('trance'+hash);
        var msg = hash,func = msg.split('|')[0] , parm = msg.split('|')[1];
         if(func == 'setHeight'){
            parent.parent.window.document.getElementById('thridparty').height = parm;
            };

 通过hash 也可以,但是 不知道为何在实现的时候 出现莫名其妙的hash被截断的情况,改用search解决。 

原文地址:https://www.cnblogs.com/trance/p/2345215.html