FrontEnd/JavaScript

[JavaScript] postMessage 사용 예제

모야이거였어 2022. 2. 8. 20:11

예제 설명

iframe 태그에서 co2.html을 참조하는데, co1.html에서 버튼을 누르면 co2.html으로 가서 메세지를 전송

 

 

 

예제 코드

co1.html

<!DOCTYPE html>
<html>
<head>
<meta>
<title>Parent</title>
<script type="text/javascript">
function sendMessage(){
    var dest = document.getElementById("co2");
    dest.contentWindow.postMessage("CO1에서 보내는 메세지","*");
}
</script>
</head>
<body>
    <button onclick="sendMessage();">Send-&gt;</button>
    <iframe id="co2" src="co2.html" width="200" height="100"></iframe>
</body>
</html>

co2.html

<!DOCTYPE html>
<html>
<head>
<meta>
<title>Child</title>
<script>
    window.onmessage = function(e) {
        document.getElementById("message").innerHTML += e.data;
    }
</script>
</head>
<body>
<div id="message"></div>
</body>
</html>

 

 

 

예제파일

co1.html
0.00MB
co2.html
0.00MB