'window.postMessage'에 해당되는 글 1건

  1. 2011.10.25 window.postMessage 알아보기.

window.postMessage 알아보기.

ITWeb/개발일반 2011. 10. 25. 10:01
[참고 URL]
https://developer.mozilla.org/en/DOM/window.postMessage
http://www.whatwg.org/specs/web-apps/current-work/multipage/web-messaging.html#web-messaging


window.postMessage 는 cross domain 간 데이터를 주고 받는데 아주 유용한 기법을 제공 합니다.
자세한 spec 은.. 위 URL 참고 하시면 됩니다.


http://192.168.1.1/siteA.html

0. siteB 를 allow 할 allowOrigin 정의를 합니다.
var allowOrigin = "http://192.168.2.1";

1. siteB 에서 전송한 postMessage 이벤트를 catch 하기 위해서 event 등록을 합니다.
window.addEventListener("message", postMessageController, true); 또는
window.attachEvent("onmesage", postMessageController);

2. siteB 의 postMessage 이벤트를 catch 해서 실행 시킬 postMessageController 함수 작성을 합니다.
function postMessageController(e) {
    if ( e.origin === allowOrigin ) {
        // 실행 시킬 코드를 작성 하세요.
        alert(e.data); // e.data 는 siteB 에서 전달 받은 message 입니다.
    }
}

http://192.168.2.1/siteB.html

0. siteA 와 통신 하기 위한 allowOrigin 을 정의 합니다. (allowOrigin 은 그냥 임의 정의한 변수명 입니다. 바꾸셔도 되요.)
var allowOrigin = "http://192.168.1.1"; 

1. siteA 로 전달할 message 용 함수를 작성 합니다.
function sendMessage () {
    window.parent.postMessage("Hi! Good to see you.", allowOrigin);
}
이 함수를 실행 시키면 siteA 의 postMessageController 가 동작 하게 됩니다. 



이 두개 파일의 구조는 siteA.html 에 iframe 으로 siteB.html 을 embedded 시켜놓은 구조 입니다.

<html>

<head>

<title>siteA.html</title>

</head>

<body style="background:#000000;">

<iframe name="siteB" id="siteB" src="http://192.168.2.1/siteB.html" border="0" frameborder="0" width="320" height="48" scrolling="no"></iframe>

</body>

</html>



위의 샘플 pseudo code 는 siteB 에서 siteA 로 메시지를 전달 하는 예 입니다.
그렇기 때문에 siteA 에서 siteB 로 메시지를 전달하고 싶을 경우는 siteB 에 event 등록해 주시고 siteA 에서 iframe 의 window 객체를 얻어서 postMessage 를 실행 시키시면 됩니다.


 
: