postMassage之跨域通信
2020-09-10 本文已影响0人
kalrase
自行本地启动服务,修改host
parent.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>doding.com</h1>
<iframe src="http://tohao.com:9413" frameborder="1" id="ifr1" name="ifr1" scrolling="yes">
<p>Your Browser dose not support iframes</p>
</iframe>
<input type="text" id="message">
<input type="button" value="this is message" onclick="sendIt()">
<script>
//父到子的通信
var myIframe = document.getElementById('ifr1')
function sendIt() {
myIframe.contentWindow.postMessage(document.getElementById('message').value, 'http://tohao.com:9413')
}
//监听子到父的消息
window.addEventListener('message', function (e) {
console.log('父级:', e);
// e.source.postMessage('received'+'--parent', e.origin); //向原网页返回信息
//执行动作
// window.open('http://www.baidu.com')
})
</script>
</body>
</html>
子页面
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>tohao.com</h1>
<input type="button" name="demoBtn" id="demoBtn" value="click">
</body>
<script>
localStorage.setItem('roomId', '1335380');
//监听父级发送的消息
window.addEventListener('message', receiver, true);
function receiver(e) {
console.log(e, 'e');
if (e.origin == 'http://doding.com:9133') {
if (e.data == 'give u a message') {
// 回应父级消息
e.source.postMessage('received' + localStorage.getItem('roomId'), e.origin); //向原网页返回信息
} else {
alert(e.data.toString());
}
}
}
//子到父通信
document.getElementById('demoBtn').onclick = function () {
top.postMessage('hedfs', 'http://doding.com:9133')
}
</script>
</html>