Iframe 과 부모창 통신 방법

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

참조2: https://gist.github.com/pbojinov/8965299

Window.postMessage()

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

developer.mozilla.org

Iframe 과 부모창 통신 방법

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

서로다른 도메인의 부모창과 iframe 작업을 하면서 공부한내용을 정리한다.

parent 페이지

     if (window.addEventListener) {

            window.addEventListener("message"handlerFunctionfalse);        

     } else if (window.attachEvent) {

                window.attachEvent("onmessage"handlerFunction);

     }

     function handlerFunction(event){

        console.log(event.data) -> iframe에서 보내온 값이 들어온다. close 출력

       //origin 체크

       if(event.origin==targetDomain&&event.data=='type') {

       }

     }

     function createFrame(){

        .....

            var elFrame = document.createElement("IFRAME");

            elFrame.addEventListener("load"function() {

                this.contentWindow.postMessage('hello child''*'); // send trigger message

            });

     }

iframe 페이지

    if (window.addEventListener) {

        window.addEventListener("message", iframeHandler, false);        

    } 

    else if (window.attachEvent) {

        window.attachEvent("onmessage", iframeHandler);

    }

function iframeHandler(event) {

console.log( event.origin +' : '+event.data )  --> parent의 도메인주소 : hello child 출력

  window.parent.postMessage('close', '*');  <--- * 말고 부모의 도메인을 써야 한다.

}

부모 페이지와 iframe의 도메인이 서로 다르다면 보안상의 이유로 통신을 할 수 없다.

통신을 할 수 없다는 의미는 window.parent와 같이 부모창의 DOM에 접근할 수 없다는 것이다.

however, for security reasons, the parent page could not communicate with the child Iframe, nor could the child communicate with the parent.

허나, postMessage를 이용하면 parent -> child 또는 child -> parent로의 메세지 전송을 할 수 있다.

child -> parent 로의 메세지 전송 방법에 대해서 알아보면 다음과 같다.

1. parent 페이지가 로딩된다.

2. parent 페이지의 DOM 생성이 완료되면 이벤트 리스너를 등록한다.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function() {

window.addEventListener("message", processFn, false);

});

function processFn(event) {

var bla = event.data;

alert(bla);

}

function sendChildMessage() {

document.getElementById("ifr").contentWindow.postMessage('sent message from parent.html', '*');

}

</script>

<iframe name="ifr" id="ifr" width="50" height="50" frameborder="0" scrolling="no" src="child.html"></iframe>

<input type="button" value="send child message" onclick="sendChildMessage();">

3. child 페이지의 DOM 생성이 완료되면 parent로 메세지를 전송한다.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script type="text/javascript">

$(document).ready(function() {

            window.parent.postMessage("sent message from child.html", "*");   // '*' on any domain        

            window.addEventListener("message", receiveParentMessage, false);

});

    function receiveParentMessage(e) {

        alert(e.data);

    }

</script>