<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Html5 postMessage</title>
<style>
#otherWin {
width: 600px;
height: 400px;
background-color: #cccccc;
}
</style>
</head>
<body>
<button id="btn">open</button>
<button id="send">send</button>
<iframe src="http://jhssdemo.duapp.com/demo/h5_postmessage/win.html"
id="otherWin"></iframe>
<br/><br/>
<input type="text" id="message">
<input type="button"
value="Send to child.com" id="sendMessage" />
<script>
window.onload = function() {
var btn = document.getElementById('btn');
var btn_send = document.getElementById('send');
var sendBtn = document.getElementById('sendMessage');
var win = document.getElementById("otherWin").contentWindow;
btn.onclick = function() {
win = window.open('http://jhssdemo.duapp.com/demo/h5_postmessage/win.html', 'popUp');
}
btn_send.onclick = function() {
win.postMessage('Hello', 'http://jhssdemo.duapp.com/');
}
function sendIt(e){
document.getElementById("otherWin").contentWindow
.postMessage(
document.getElementById("message").value,
"http://jhssdemo.duapp.com/");
}
sendBtn.onclick = function(e) {
sendIt(e);
};
};
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Html5 postMessage</title>
<style>
#txt {
width: 500px;
height: 300px;
background-color: #cccccc;
}
</style>
</head>
<body>
<h1>The New Window</h1>
<div id="txt"></div>
<script>
window.onload = function() {
var text = document.getElementById('txt');
function receiveMsg(e) {
console.log("Got a message!");
console.log("nMessage: " + e.data);
console.log("nOrigin: " + e.origin);
text.innerHTML = "Got a message!<br>" +
"Message: " + e.data +
"<br>Origin: " + e.origin;
}
if (window.addEventListener) {
window.addEventListener('message', receiveMsg, false);
}else {
window.attachEvent('message', receiveMsg);
}
};
</script>
</body>
</html>