iframe跨域设置高度

こちらのページをそのまま参考にしてhttp://ja.w3support.net/index.php?db=so&id=153152
iframeで別ドメインにあるページを開いた時に、自動的にheightを調整する方法を試してみた。
(※ 別ドメインにあるファイルにjsを追加する必要あり)

別ドメインのhtmlに手を加えずに出来たら、確実に嬉ションしちゃうけど難しいみたいすなぁ。


構成
www.foo.com/home.html, which iframes
└> www.bar.net/framed.html, which iframes
            └> www.foo.com/helper.html

記述例

www.foo.com/home.html
<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> 

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> 

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> 

追記
結局iframe先のページに書き込むの事に代わりがないのなら
window.postMessage() を使って、クロスドメインの iframe の高さを設定する検証 – 写経日記の方がシンプルで素敵だ。

でもwindow.postMessage()というのを使っているので
以下のように(見よう見まねで)window.attachEventを追加してもIE7以下は広がらなかったです。

構成

www.foo.com/parent.html
└> www.bar.net/iframe.html
parent.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript">
if (window.addEventListener) { //for W3C DOM
    window.addEventListener("message", receiveSize, false);
} else if (window.attachEvent) { //for IE
window.attachEvent("onmessage",receiveSize);
}
    function receiveSize(e) {
        if (e.origin === "http://www.bar.net/") // for security: set this to the domain of the iframe - use e.uri if you need more specificity
            document.getElementById("bar").style.height = e.data + "px";
    }
</script>
</head>
<body>
<iframe id="bar" src="http://www.bar.net/iframe.html" scrolling="no" > </iframe>
</body>
</html>

www.bar.net/iframe.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<script type="text/javascript">
if (window.addEventListener) { //for W3C DOM
    window.addEventListener("load", postSize, false);
}else if (window.attachEvent) { //for IE
window.attachEvent("onload",postSize);
}
    function postSize(e){
        var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);
        if (typeof target != "undefined" && document.body.scrollHeight)
            target.postMessage(document.getElementById("foo").scrollHeight, "*");
    }

</script>
</head>
<body>
<div id="foo" style="height: 1500px; background:red;"></div>
</body>
</html>


参考资料:
http://d.hatena.ne.jp/bannyan/20090820/1250789189
http://blog.sakurachiro.com/2010/11/iframe-resize/
https://developer.mozilla.org/Ja/DOM/Window.postMessage

你可能感兴趣的:(JavaScript)