통합검색

Javascript

[Javascript] Crossdomain iframe 컨텐츠 높이에 맞게 자동 조절



iframe 내부의 문서가 외부 웹페이지(Cross Domain)인 경우
내부 iframe의 높이, 폭 크기에 맞게 iframe 사이즈를 자동 조정하는 script 코드.


[!]iframe이 삽입되는 부모 페이지[/!]
<iframe src="document.html" id="iframeWrap" frameborder="0" scrolling="no"></ifrmae>

<script>
    // iframe auto height
    let iframe = document.querySelector("#iframeWrap");
    window.addEventListener('message', function(e) {
        let message = e.data;

        iframe.style.height = message.height + 80 + 'px';
        iframe.style.width = message.width + 'px';
    } , false);
</script>

[!]iframe 내부[/!]
<script>
$(function() {
    // iframe auto height
    let auto_height = function() {
        let message = { height: $('#wmanager').height(), width: $('#wmanager').width() };
        window.top.postMessage(message, "*");
    }

    $(window).on({
        'load' : auto_height
    })
})
</script>