티스토리 뷰

부모창에서 iframe을 이용해 자식 Modal 창을 띄우고, 자식 Modal 창에서 닫기 요청을 하는 방법에 대해 간략하게 알아보겠습니다.


1. 부모창

  • 부모창 소스 작성(parent.html)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Parent Window</title>
    <style>
        .modal {
            display: none;
            position: fixed; 
            z-index: 1; 
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto; 
            background-color: rgb(0,0,0); 
            background-color: rgba(0,0,0,0.4); 
        }
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
        }
    </style>
</head>
<body>
    <h2>Parent Window</h2>
    <button onclick="openModal()">Open Modal</button>

    <div id="myModal" class="modal">
        <div class="modal-content">
            <iframe id="modalIframe" src="" style="width:100%; height:300px; border:none;"></iframe>
        </div>
    </div>

    <script>
        function openModal() {
            var modal = document.getElementById("myModal");
            var iframe = document.getElementById("modalIframe");
            iframe.src = "child.html";
            modal.style.display = "block";
        }

        function closeModal() {
            var modal = document.getElementById("myModal");
            modal.style.display = "none";
        }

        // 자식 창에서 메시지를 받을 이벤트 리스너 추가
        window.addEventListener("message", function(event) {
            if (event.data === "closeModal") {
                closeModal();
            }
        });
    </script>
</body>
</html>
  • openModal() 함수를 통해 iframe의 경로를 지정하고 modal 창을 활성화합니다.
  • closeModal() 함수를 통해 modal 창을 비활성화합니다.
  • message 이벤트 리스너를 통해 자식창으로 "closeModal"이라는 메시지를 받게 되면 closeModal() 함수를 호출합니다.

 

2. 자식창

  • 자식창 소스 작성(child.html)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Child Window</title>
</head>
<body>
    <h2>Child Window</h2>
    <button onclick="closeParentModal()">Close Modal</button>

    <script>
        function closeParentModal() {
            // 부모 창으로 메시지 전송하여 모달 닫기 요청
            window.parent.postMessage("closeModal", "*");
        }
    </script>
</body>
</html>
  • closeParentModal() 함수를 통해 부모창에 "closeModal" 메시지를 전송합니다.



3. 오류발생

  • addEventListener 오류 시 다른 함수 사용
window.onmessage = function(event) {
    if (event.data === "closeModal") {
        closeModal();
    }
};
  • IE 나 Mozila의 버전이 낮은 경우, addEventListener를 지원하지 않는다면 onmessage를 이용할 수 있습니다.



4. 버전별

  • 버전별 적용
function addEventListenerCompat(element, eventName, listener) {
    if (element.addEventListener) {
        // 최신 브라우저에서 사용하는 방식
        element.addEventListener(eventName, listener, false);
    } else if (element.attachEvent) {
        // 구식 브라우저(IE8 이하)에서 사용하는 방식
        element.attachEvent("on" + eventName, listener);
    } else {
 		// 위 두 가지 방식이 모두 지원되지 않는 아주 구식 브라우저를 위한 대체 방식
        element["on" + eventName] = listener;
    }
}

// 메시지 이벤트 리스너 추가
addEventListenerCompat(window, "message", function(event) {
    if (event && event.data) {
        if (event.data === "closeModal") {
            closeModal();
        }
    }
});
  • 위처럼 버전에 맞게 이벤트 리스너를 추가할 수 있습니다.

 

감사합니다.

최근에 올라온 글
Total
Today
Yesterday