iframeの幅と高さを調整して、コンテンツに合わせる

I need a solution for auto-adjusting the width and height of an iframe to barely fit its content.ポイントは、「iframe」が読み込まれた後に、幅と高さを変更できることです。iframeに含まれるボディの寸法変更に対応するためには、イベントアクションが必要だと思います。

ソリューション
<script type="application/javascript">

function resizeIFrameToFitContent( iFrame ) {

    iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
    iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
}

window.addEventListener('DOMContentLoaded', function(e) {

    var iFrame = document.getElementById( 'iFrame1' );
    resizeIFrameToFitContent( iFrame );

    // or, to resize all iframes:
    var iframes = document.querySelectorAll("iframe");
    for( var i = 0; i < iframes.length; i++) {
        resizeIFrameToFitContent( iframes[i] );
    }
} );

</script>

解説 (23)

クロスブラウザ[jQueryプラグイン][1]。

クロスブラウザ、クロスドメインの [ライブラリ][2] です。mutationObserver を使って iFrame のサイズをコンテンツに合わせて維持し、postMessage を使って iFrame とホストページの間で通信します。jQueryを使用してもしなくても動作します。

[1]: https://github.com/house9/jquery-iframe-auto-height [2]: https://github.com/davidjbradshaw/iframe-resizer

解説 (1)

jQueryを使いたくないという方のために、クロスブラウザ対応のソリューションをご紹介します。

/**
 * Resizes the given iFrame width so it fits its content
 * @param e The iframe to resize
 */
function resizeIframeWidth(e){
    // Set width of iframe according to its content
    if (e.Document && e.Document.body.scrollWidth) //ie5+ syntax
        e.width = e.contentWindow.document.body.scrollWidth;
    else if (e.contentDocument && e.contentDocument.body.scrollWidth) //ns6+ & opera syntax
        e.width = e.contentDocument.body.scrollWidth + 35;
    else (e.contentDocument && e.contentDocument.body.offsetWidth) //standards compliant syntax – ie8
        e.width = e.contentDocument.body.offsetWidth + 35;
}
解説 (3)