-
Window.postMessage, Iframe과 부모창의 통신카테고리 없음 2019. 12. 17. 17:03
참조: 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
window.postMessage() 메소드는 Window 오브젝트 사이에서 안전하게 cross-origin 통신을 할 수 있게 합니다. 예시로, 페이지와 생성된 팝업 간의 통신이나, 페이지와 페이지 안의 iframe 간의 통신에 사용할 수 있습니다.
서로다른 도메인의 부모창과 iframe 작업을 하면서 공부한내용을 정리한다.
parent 페이지
if (window.addEventListener) {
window.addEventListener("message", handlerFunction, false);
} 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', '*'); <--- * 말고 부모의 도메인을 써야 한다.
}