IFRAME과 메시지 전달
2016년 08월 13일
window.postMessage를 이용한 메시지 전달
window.postMessage
를 이용하면 iframe 안의 페이지와 메시지를 주고받을 수 있다.
iframe의 도메인이 다른 경우에도 사용할 수 있으며 IE8에서도 사용이 가능하다고 되어있으나 안되는 경우가 종종 있는 것 같다. (Can I Use)
메시지 송신
window.postMessage(data, [ports], targetOrigin);
- data: 전달할 메시지 (string)
- ports: 메시지 포트 (생략 가능)
- targetOrigin: 메시지를 수신받는 도메인. 특정 도메인이 아니라면
*
로 지정한다.
메시지 수신
window.addEventListener("message", function (e) {
// e.data가 전달받은 메시지
console.log(e.data);
});
- e.data: 전달받은 메시지
- e.origin: 송신자의 도메인
예시
https://302chanwoo.com/lab/postMessage/parent.html
1. 부모가 자식 iframe에 메시지 전달
부모 HTML (메시지 전송할 버튼과 iframe 생성)
<button id="btn">자식에게 메시지 전송</button>
<iframe
id="child"
src="/lab/postMessage/child.html"
width="100%"
height="300px"
frameborder="0"
></iframe>
부모 JavaScript (자식 iframe에 메시지 전달)
var btn = document.getElementById("btn"); // 메시지 전송 버튼
var child = document.getElementById("child"); // iframe
// 버튼 클릭하면 메시지 전달 함수 호출
btn.addEventListener("click", function (e) {
sendMsgToChild("아들! 딸!");
});
// 자식에게 메시지 전달
function sendMsgToChild(msg) {
child.contentWindow.postMessage(msg, "*");
}
postMessage
함수는 window
객체에 접근해서 실행해야 하는데, iframe의 window
에 접근하려면 contentWindow
를 사용해야 한다.
contentWindow
속성은 iframe에 의해 생성된 Window
객체를 말한다.
자식 iframe의 JavaScript (부모로부터 메시지 수신)
window.addEventListener("message", receiveMsgFromParent);
// 부모로부터 메시지 수신
function receiveMsgFromParent(e) {
// e.data가 전달받은 메시지
console.log("부모로부터 받은 메시지 ", e.data);
}
2. 자식 iframe이 부모에게 메시지 전달
부모 JavaScript (자식으로부터 메시지 수신)
// 메시지 수신 받는 eventListener 등록
window.addEventListener("message", receiveMsgFromChild);
// 자식으로부터 메시지 수신
function receiveMsgFromChild(e) {
console.log("자식으로부터 받은 메시지 ", e.data);
}
자식 iframe의 HTML (전송 버튼 생성)
<button id="btn">부모에게 메시지 전송</button>
자식 iframe의 JavaScript (부모에게 메시지 전달)
var btn = document.getElementById("btn");
btn.addEventListener("click", function (e) {
sendMsgToParent("엄마! 아빠!");
});
// 부모에게 메시지 전달
function sendMsgToParent(msg) {
window.parent.postMessage(msg, "*");
}
window.parent
는 자식 iframe에서 부모의 window
객체를 나타낸다.