Cross Document messaging 통신
다른 사이트 페이지끼리 통신 하기


참조 URL
  1. https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
  2. http://m.mkexdev.net/75
  3. http://jjeong.tistory.com/476
  4. postMessage를 이용한 크로스도메인간 iframe 리사이징
  5. http://jsonobject.tistory.com/53





[그림1] postMessage를 통한 크로스 사이트 통신



 '그림1'에서와 같이 페이지에서 iFrame로 임베이딩된 상태에서는 브라우저의 보안 정책으로 인해 자바스크립트를 통해 페이지간 통신을 할 수 없었다. 하지만 postMessage를 통해서 가능하게 되었다. 지원하는 브라우저는 아래 '그림2'에서와 같이 IE8에서부터 지원이 되므로 거의 대부분의 브라우저에서 지원된다고 보면 될 것이다.



[그림2] postMessage 브라우저 호환표

http://caniuse.com/#feat=x-doc-messaging )


 이제 postMessage의 사용법에 대해서 알아 보자



데이터 송신하기


데이터를 송신하기 위해서는 window 객체의 postMessage 함수를 사용하면 된다


[코드1] 데이터 송신



data: 전달할 메세지, 즉 송신할 데이터를 지정한다

ports: 메세지를 전송할 포트(생략 가능)

targetOrigin: 타켓 도메인,  즉 메세지를 수신받는 도메인을 지정한다 대상이 특정 도메인이 아니라면 * 로 지정한다 




데이터 수신하기


데이터를 수신하는 측에서는 단순히 window 객체의 message 이벤트를 구현하면 된다


[코드2] 데이터 수신



data: 메세지 즉 송신한 데이터이다

origin: 메세지를 보내는 곳의 도메인 정보 크로스 도메인 환경이라면 상대 도메인을 확인하는 것이 보안상 좋다

source: 메세지를 보내는 윈도우 객체 



이제 이 코드를 가지고 아래 예제 코드로 활용법을 보도록 하자.



[코드] 송신쪽 페이지 코드



[코드] 수신쪽 페이지 코드



Syntax

otherWindow.postMessage(message, targetOrigin, [transfer]);



otherWindow

A reference to another window; such a reference may be obtained, for example, using the contentWindow property of an iframe element, the object returned by window.open, or by named or numeric index on window.frames.


message

Data to be sent to the other window.


targetOrigin

Specifies what the origin of otherWindow must be for the event to be dispatched, either as the literal string "*" (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of otherWindow's document does not match that provided in targetOrigin, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if postMessage were used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. Always provide a specific targetOrigin, not *, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site.


transfer [Optional]

Is a sequence of Transferable objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no more usable on the sending side.












+ Recent posts