본문 바로가기
WWWEB/Script

[ js ] 크로스도메인에서 iframe 높이값 자동 처리하기

by 미니토이 2023. 3. 2.

서로 다른 도메인을 가진 아이프레임 페이지를 부른 후 높이값을 맞춰주고 싶은데, 

 

top.document, parent.frame 등과 같이 직접 접근이 불가하다.

 

콘솔에 나오는 Blocked a frame ...... cross-origin frame.

 

이 경우 window.postMessage() method를 사용하면 되는데,

이 method는 윈도우 오브젝트 사이에서 안전하게 cross-origin 통신을 할 수 있게 한다.

 

아래 예시 코드로 확인해보자.

 

 

부모 페이지 (parent-site)

function fn_postMessageController( e ){
    if( e.origin === "http://child-site.com" ){
    	document.querySelector( "#iframe-id" ).setAttribute( "height", parseInt( e.data ) );
    }
}

if( window.addEventListener ){
    window.addEventListener( "message", fn_postMessageController, true );
} else if( window.attachEvent ){
    window.attachEvent( "onmessage", fn_postMessageController );
}

 

 

자식 페이지 (child-site)

const contentsHeight = document.querySelector( "#contents" ).offsetHeight;
window.parent.postMessage( contentsHeight, "http://parent-site.com" );

 

 

이때 주의할 점은 도메인을 잘 맞춰서 작성해야 한다.

잘 되지 않는 경우 콘솔로 e.origin값을 찍어서 확인해보자.

 

 

 

https://developer.mozilla.org/ko/docs/Web/API/Window/postMessage

 

Window.postMessage() - Web API | MDN

window.postMessage() 메소드는 Window 오브젝트 사이에서 안전하게 cross-origin 통신을 할 수 있게 합니다. 예시로, 페이지와 생성된 팝업 간의 통신이나, 페이지와 페이지 안의 iframe 간의 통신에 사용할

developer.mozilla.org

 

728x90
반응형

댓글