根据内容调整iframe大小

lar*_*ssg 496 javascript iframe widget

我正在开发类似iGoogle的应用程序.来自其他应用程序(在其他域上)的内容使用iframe显示.

如何调整iframe的大小以适应iframe内容的高度?

我试图破译谷歌使用的javascript,但是它被混淆了,到目前为止搜索网络已经没有结果.

更新:请注意,内容是从其他域加载的,因此适用同源策略.

Con*_*oyP 581

我们遇到了这种类型的问题,但与您的情况相反 - 我们将iframed内容提供给其他域上的网站,因此相同的原始策略也是一个问题.经过长达数小时的拖网搜索后,我们最终找到了一个(有点......)可行的解决方案,您可以根据自己的需要进行调整.

围绕相同的原始策略有一种方法,但它需要更改iframed内容和框架页面,所以如果你无法双方请求更改,这种方法对你来说不是很有用,我耽心.

有一个浏览器怪癖允许我们绕过相同的原始策略--javascript可以与其自己的域上的页面进行通信,也可以与iframed的页面进行通信,但从不与其进行框架的页面进行通信,例如,如果您有:

 www.foo.com/home.html, which iframes
 |-> www.bar.net/framed.html, which iframes
     |-> www.foo.com/helper.html
Run Code Online (Sandbox Code Playgroud)

然后home.html可以与framed.html(iframed)和helper.html(相同的域)进行通信.

 Communication options for each page:
 +-------------------------+-----------+-------------+-------------+
 |                         | home.html | framed.html | helper.html |
 +-------------------------+-----------+-------------+-------------+
 | www.foo.com/home.html   |    N/A    |     YES     |     YES     |
 | www.bar.net/framed.html |    NO     |     N/A     |     YES     |
 | www.foo.com/helper.html |    YES    |     YES     |     N/A     |
 +-------------------------+-----------+-------------+-------------+
Run Code Online (Sandbox Code Playgroud)

framed.html可以发送消息helper.html(iframed)但不发送 home.html(子节点不能与父节点进行跨域通信).

这里的关键是,helper.html能够接收来自消息framed.html,并且还可以沟通home.html.

所以基本上,当framed.html加载时,它会运行它自己的高度,告诉helper.html它将消息传递给home.html,然后可以调整其中的iframe的大小framed.html.

我们发现,从传递消息最简单的方法framed.htmlhelper.html是通过URL参数.为此,请指定framed.htmliframe src=''.当它onload发射时,它会评估自己的高度,并在此时将iframe的src设置为helper.html?height=N

这里有一个关于facebook如何处理它的解释,这可能比我的上面稍微清楚一点!


www.foo.com/home.html,需要以下javascript代码(这可以从任何域上的.js文件加载,顺便说一句..):

<script>
  // Resize iframe to full height
  function resizeIframe(height)
  {
    // "+60" is a general rule of thumb to allow for differences in
    // IE & and FF height reporting, can be adjusted as required..
    document.getElementById('frame_name_here').height = parseInt(height)+60;
  }
</script>
<iframe id='frame_name_here' src='http://www.bar.net/framed.html'></iframe>
Run Code Online (Sandbox Code Playgroud)

www.bar.net/framed.html:

<body onload="iframeResizePipe()">
<iframe id="helpframe" src='' height='0' width='0' frameborder='0'></iframe>

<script type="text/javascript">
  function iframeResizePipe()
  {
     // What's the page height?
     var height = document.body.scrollHeight;

     // Going to 'pipe' the data to the parent through the helpframe..
     var pipe = document.getElementById('helpframe');

     // Cachebuster a precaution here to stop browser caching interfering
     pipe.src = 'http://www.foo.com/helper.html?height='+height+'&cacheb='+Math.random();

  }
</script>
Run Code Online (Sandbox Code Playgroud)

内容www.foo.com/helper.html:

<html> 
<!-- 
This page is on the same domain as the parent, so can
communicate with it to order the iframe window resizing
to fit the content 
--> 
  <body onload="parentIframeResize()"> 
    <script> 
      // Tell the parent iframe what height the iframe needs to be
      function parentIframeResize()
      {
         var height = getParam('height');
         // This works as our parent's parent is on our domain..
         parent.parent.resizeIframe(height);
      }

      // Helper function, parse param from request string
      function getParam( name )
      {
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
          return "";
        else
          return results[1];
      }
    </script> 
  </body> 
</html>
Run Code Online (Sandbox Code Playgroud)

  • +1为详细解释为什么这是有效的 (114认同)
  • 太好了,谢谢!我做了几个补充:使用jQuery获取framed.html中的身高(FF问题,身体不断增长):var height = $(document.body).height(); 使用body onload事件在home.html中创建框架,类似于framed.html中的方法.地址不在FF和Safari中刷新时更新帧. (9认同)
  • 我建议给iframe id = frame_name_here一个默认的高度属性,例如height ="2000".这意味着当页面加载时,框架内容是可见的.调整大小时,没有"闪烁".调整大小正在缩小/扩展到页面折叠以下.如果您知道iframed内容的最大高度,那么使用该值......这也会带来更好的noscript体验. (8认同)
  • 充满了洞察力.我想知道为什么igoogle.com有一个helper.html文件!谢谢 (7认同)
  • 天才!除了Abdullah的补充:除了将body onload设置为调用`parentIframeResize()`之外,我还使用JQuery来捕获页面加载和任何调整大小的事件:`$(document).ready(iframeResizePipe); $(window).resize(iframeResizePipe);`这允许我设置iframe`width ="100%"`并且如果窗口宽度改变以使文本换行或其他东西,内框将识别它需要调整大小. (5认同)
  • 七年后,我发现仍然是最好的跨浏览器,跨域解决方案.布拉沃. (3认同)
  • @Frederico,这种方法确实有效,但需要修改解决方案才能在最新版本的FF和Chrome中使用.如果滚动高度大于正在渲染的页面,则滚动高度将不正确地使用iframe高度.这导致iframe在每次翻页时可能增加60px.所需的修复是在框架式HTML中包含ID'd元素.获取它的滚动高度而不是文档,它就像一个冠军. (2认同)
  • 不幸的是,这似乎不再起作用.我仔细地实现了这一点,但在Chrome控制台中收到以下javascript错误:未捕获的DOMException:阻止来自原始"http://www.example.com"的框架访问跨源框架. (2认同)

Ahm*_*hmy 81

如果您不需要处理来自其他域的iframe内容,请尝试使用此代码,它将完全解决问题并且很简单:

<script language="JavaScript">
<!--
function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}
//-->
</script>

<iframe src="usagelogs/default.aspx" width="100%" height="200px" id="iframe1" marginheight="0" frameborder="0" onLoad="autoResize('iframe1');"></iframe>
Run Code Online (Sandbox Code Playgroud)

  • 将元素本身传递给函数可能更为理想,以避免所有的`document.getElementById(id)`并简化代码. (9认同)
  • 我没有得到它...你检查document.getElementById的存在,然后在被检查区域之外调用它? (7认同)
  • @Eugenio和包括我在内的其他人,为了解决这个最后的问题:请参阅http://stackoverflow.com/questions/3053072/iframe-resizing-with-scrollheight-in-chrome-safari在你要求内部文件的高度之前在iframe中,您应该将iframe对象的高度设置为"auto".请注意,您应该使用style.height而不仅仅是上面的答案中的高度 (6认同)
  • 这个解决方案,就像我尝试的所有其他解决方案一样,只有在高度增加时才有效,如果从高页面导航到较短的高度,高度仍然根据第一个高度设置.有没有人找到解决这个问题的方法? (4认同)

Chr*_*cob 40

https://developer.mozilla.org/en/DOM/window.postMessage

window.postMessage()

window.postMessage是一种安全启用跨源通信的方法.通常,当且仅当执行它们的页面位于具有相同协议(通常是http),端口号(80是http的默认值)和主机(模数)的位置时,才允许不同页面上的脚本相互访问. document.domain由两个页面设置为相同的值).window.postMessage提供了一种受控机制,可以在正确使用时以安全的方式规避此限制.

摘要

window.postMessage,当被调用时,会导致在任何必须执行的挂起脚本完成时在目标窗口调度MessageEvent(例如,如果从事件处理程序调用window.postMessage,之前设置的挂起超时等,则保留事件处理程序. ).MessageEvent具有类型消息,一个data属性,设置为提供给window.postMessage的第一个参数的字符串值,一个origin属性,对应于窗口调用window.postMessage时窗口中主文档的原点.调用了postMessage,并调用了一个source属性,该属性是调用window.postMessage的窗口.(事件的其他标准属性与其预期值一起出现.)

iframe的调整器库使用的postMessage保持一个iFrame尺寸为它的内容,随着MutationObserver检测改动的内容和不依赖于jQuery的.

https://github.com/davidjbradshaw/iframe-resizer

jQuery:跨域脚本编写的好处

http://benalman.com/projects/jquery-postmessage-plugin/

有调整iframe窗口大小的演示......

http://benalman.com/code/projects/jquery-postmessage/examples/iframe/

本文介绍如何删除对jQuery的依赖... Plus有很多有用的信息和其他解决方案的链接.

http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/

Barebones的例子......

http://onlineaspect.com/uploads/postmessage/parent.html

关于window.postMessage的HTML 5工作草案

http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages

John Resig关于跨窗口消息传递

http://ejohn.org/blog/cross-window-messaging/

  • 本来很高兴看到你回答问题,而不是解释一个有助于解决方案的辅助技术.. (3认同)
  • postMessage似乎是X-Browser.只有IE必须要处理错误或事情:1.仅在帧或iframe之间进行通信2.仅能发布字符串.请参阅:http://caniuse.com/x-doc-messaging (2认同)

小智 9

使用jQuery的最简单方法:

$("iframe")
.attr({"scrolling": "no", "src":"http://www.someotherlink.com/"})
.load(function() {
    $(this).css("height", $(this).contents().height() + "px");
});
Run Code Online (Sandbox Code Playgroud)

  • 不按要求跨域. (14认同)

Mac*_*att 6

http://www.phinesolutions.com/use-jquery-to-adjust-the-if​​rame-height.html上的解决方案效果很好(使用jQuery):

<script type=”text/javascript”>
  $(document).ready(function() {
    var theFrame = $(”#iFrameToAdjust”, parent.document.body);
    theFrame.height($(document.body).height() + 30);
  });
</script>
Run Code Online (Sandbox Code Playgroud)

我不知道你需要增加30个长度...... 1对我有用.

仅供参考:如果您的iFrame上已经有"height"属性,则只需添加style ="height:xxx".这可能不是你想要的.

  • 不是跨域,没有. (7认同)

Sel*_*ani 6

最后,我找到了一些其他解决方案,可以使用window.postMessage(message, targetOrigin);. 我在这里解释我是如何做到的。

站点 A = http://foo.com 站点 B = http://bar.com

SiteB 正在加载 siteA 网站内

SiteB网站有这条线

window.parent.postMessage("Hello From IFrame", "*"); 
Run Code Online (Sandbox Code Playgroud)

或者

window.parent.postMessage("Hello From IFrame", "http://foo.com");
Run Code Online (Sandbox Code Playgroud)

然后站点A有以下代码

// Here "addEventListener" is for standards-compliant web browsers and "attachEvent" is for IE Browsers.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];


var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child IFrame window
eventer(messageEvent, function (e) {
   alert(e.data);
   // Do whatever you want to do with the data got from IFrame in Parent form.
}, false); 
Run Code Online (Sandbox Code Playgroud)

如果你想添加安全连接,你可以使用这个 if 条件 eventer(messageEvent, function (e) {})

if (e.origin == 'http://iframe.example.com') {
    alert(e.data); 
    // Do whatever you want to do with the data got from IFrame in Parent form.
}
Run Code Online (Sandbox Code Playgroud)

IE浏览器

IFrame内部:

 window.parent.postMessage('{"key":"value"}','*');
Run Code Online (Sandbox Code Playgroud)

外部:

 eventer(messageEvent, function (e) {
   var data = jQuery.parseJSON(e.data);
   doSomething(data.key);
 }, false);
Run Code Online (Sandbox Code Playgroud)