오늘도 알차게 즐겁게 ~ !!
자세히보기

IT/SW Dev.

HTML iframe 동적(자동) 높이 조절 가이드 코드 생성 (JavaScript 활용)

부티형 2025. 3. 23. 09:57
728x90
반응형

 

Designed by Freepik

 

index.html(부모 페이지)에서 iframe 으로 target.html를 로딩할때 다음과 같이 iframe 사이즈를 자동 조절할 수 있게 코드를 작성한다.

 

코드 설명

  1. iframe의 onload 이벤트를 활용하여 target.html의 높이를 감지하고, 부모 iframe의 높이를 조절함.
  2. resize 이벤트를 감지하여 iframe 크기를 업데이트함.
  3. postMessage를 활용하면, target.html 내부의 크기 변화를 부모 창이 정확히 감지 가능함.

 

Index.html>

반응형
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Iframe Resize Example</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }
        .iframe-container {
            width: 100%;
            display: flex;
            justify-content: center;
        }
        iframe {
            width: 100%;
            border: none;
        }
    </style>
</head>
<body>

<div class="iframe-container">
    <iframe id="contentFrame" src="target.html"></iframe>
</div>

<script>
    function resizeIframe(height) {
        const iframe = document.getElementById("contentFrame");
        iframe.style.height = height + "px";
    }

    // target.html에서 메시지 받기
    window.addEventListener("message", (event) => {
        if (event.data && event.data.type === "resize") {
            resizeIframe(event.data.height);
        }
    });

    // 창 크기 변경 시 iframe 크기 재조정 (초기 로드 포함)
    window.addEventListener("resize", () => {
        document.getElementById("contentFrame").contentWindow.postMessage({ type: "requestHeight" }, "*");
    });

    // 초기 로드 시에도 높이 요청
    window.onload = () => {
        document.getElementById("contentFrame").contentWindow.postMessage({ type: "requestHeight" }, "*");
    };
</script>

</body>
</html>

 

targert.html>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Target Page</title>
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: lightgray;
            font-size: 20px;
        }
        .content {
            width: 100%;
            min-height: 500px; /* 최소 높이 설정 */
        }
    </style>
</head>
<body>

<div class="content">
    <p>이곳은 target.html 입니다.</p>
    <p>부모 iframe이 자동으로 크기를 조절합니다.</p>
</div>

<script>
    function sendHeight() {
        const height = document.body.scrollHeight;
        window.parent.postMessage({ type: "resize", height }, "*");
    }

    // 부모 창에서 요청하면 높이 전송
    window.addEventListener("message", (event) => {
        if (event.data && event.data.type === "requestHeight") {
            sendHeight();
        }
    });

    // 내용 변경 감지하여 높이 자동 조절
    const observer = new MutationObserver(sendHeight);
    observer.observe(document.body, { childList: true, subtree: true, attributes: true });
    
    // 페이지 로드 시에도 높이 전송
    window.onload = sendHeight;
</script>

</body>
</html>

 

동작 방식

  1. target.html이 로드될 때, postMessage를 이용해 index.html에 자신의 높이를 전달함.
  2. index.html에서는 해당 메시지를 받아 iframe 높이를 조절함.
  3. target.html의 내용이 변경될 경우, MutationObserver를 이용해 자동으로 부모에게 높이를 다시 전송함.
  4. 부모 페이지(index.html)에서 창 크기(resize 이벤트)가 변경되면 target.html에 높이를 요청하여 재조정함.
728x90
반응형