JavaScript实现iframe自动高度调整与跨域通信方案

作者:异步漫步

时间:2026-10-29

浏览:324

本文介绍如何在主域名不同的情况下,通过嵌套代理iframe解决JavaScript同源策略限制,实现父页面与第三方网站iframe的高度自适应通信。

文章目录

iframe跨域与高度自适应问题

JavaScript存在同源策略,当嵌套的iframe主域名不同时,通常不允许直接进行JavaScript通信。

若需在网站中嵌入其他网站的页面,可直接使用iframe引用第三方网站的地址。

然而,iframe高度固定导致无法与第三方网站内容良好融合。例如,第三方网站使用瀑布流插件进行滚动加载并自动计算高度时,会面临跨域问题。假设网站A.com中嵌入了引用B.com的iframe,此时B.com内的JavaScript无法访问A.com。因为JavaScript跨域通信要求同源,即同一主域名,这带来了挑战。

基于代理iframe的跨域通信方案

为解决此问题,可在B.com中引入一个名为C的代理iframe,该iframe加载A.com中的某个网页。这样便建立了同源关系:B.com中的iframe页面可与A.com通信。接下来只需让B与C通信,再由C通知A调整iframe高度,即可完成B到A的高度同步。当B的高度发生变化时,通知C,由C通知A调整iframe高度。B与C之间的通信可通过URL地址实现,将B.com的iframe设置为隐藏,通过改变其src地址,C即可接收信息。

代码实现示例

以下是具体代码实现。

A.com/index.html


<html>
  <script src="{$smarty.const.STATIC_URL}/js/jquery-1.7.1.min.js"></script>
  <script>
   var test = function() {
     $('#h1').html('test');
   }
   </script>
<body>
<h1 id="h1">nba.alltosun.net</h1>
<iframe id="ifm" width="760" height="100" src="http://***.sinaapp.com/"></iframe>
</body>
</html>

B.com/index.html


<html>
<head></head>
<body>
  <h1>**.appsina.com</h1>
  <button id="button">设置高度</button>
  <div id="div" style="height:200px;display:none;"></div>
  <script src="http://nba.alltosun.net/js/jquery-1.7.1.min.js"></script>
  <script>
  $(function(){
    window.ifrH = function(e){
      var searchUrl = window.location.search;
      var b = null;
       
      var getParam = function(url, param) {
        var q = url.match(new RegExp( param + "=[^&]*")),
        n = "";
        if (q && q.length) {
          n = q[0].replace(param + "=", "");
        }
        return n;
      }
       
      var f = getParam(searchUrl,"url"),
        h = getParam(searchUrl, "ifmID"),
        k = getParam(searchUrl, "cbn"),
        g = getParam(searchUrl, "mh");
       
 
      var iframeId = 'testiframe';
      var iframe = document.getElementById(iframeId);
      var divId = 'alltosun';
       
      if (!iframe){
        var iframe = document.createElement('iframe');
        iframe.id = iframeId;
        iframe.style.display = "none";
        iframe.width = 0;
        iframe.height = 0;
        document.body.appendChild(iframe);
      }
       
      if (e && e.type == "onload" && h) {
        b.parentNode.removeChild(b);
        b = null;
      }
       
      if (!b) {
        b = document.createElement("div");
        b.id = divId;
        b.style.cssText = "clear:both;"
        document.body.appendChild(b);
      }
       
      var l = b.offsetTop + b.offsetHeight;
      iframe.src = (decodeURIComponent(f) || 
          "http://*****/test2") + "&h=" + l + "&ifmID=" + (h || "ifm") + "&cbn=test" + "&mh=" + g + "&t=" + ( (+ new Date()));
       
      if (e && e.type =="onload") {
        window.onload = null;
      }
    }
     
    window.onload = function() {
      ifrH({type: "onload"});
    }
     
    // ifrH();
    $('button').click(function(){
      $('div').show();
      ifrH();
    })
  })
  </script>
</body>
</html>

C代理文件


<script>
var search = window.location.search,
getSearchParam = function (search, key) {
  var mc = search.match (new RegExp ( key + "=([^\&]*)") ),
    ret="";
  mc && mc.length && (ret = mc[0].replace( key + "=",""));
  return ret;
},
// 参数h 
h = getSearchParam(search,"h"),
ifmID = getSearchParam(search,"ifmID"),
cbn = getSearchParam(search,"cbn"),
// 宽高
mh = getSearchParam(search,"mh") || h,
isFunction = function(fn){
  return !!fn && !fn.nodeName && fn.constructor != String 
      && fn.constructor != RegExp && fn.constructor != Array 
      && (/function/i).test(fn + "");
};
 
try{
  if(parent && parent.parent){
    ifm = parent.parent.document.getElementById(ifmID);
    ifm && mh && (ifm.height=mh);
    fn=parent.parent[cbn];
    isFunction(fn) && fn.call();
    ifm=null;
  }
}catch(ex){
  console.log(ex);
}
 
</script>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章