PHP
·
发表于 5年以前
·
阅读量:8293
parent.html
window.addEventListener('message',function(e){
console.log(e.data);
if(e.data.msg==='xxx'){
//一些自己的业务逻辑
}
});
child.html
window.parent.postMessage({
msg:"xxx"
},'*');
parent.html
var myframe = document.getElementById('myframe');//获取iframe
myframe.contentWindow.postMessage({data:'parent'},childDomain);//childDomain是子页面的源(协议+主机+端口号)
child.html
window.addEventListener('message', function(e){
console.log(e.data.data);
})
注意:
测试代码部分:
parent.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iframe父级页面</title>
<style>
* {
padding: 0;
margin: 0;
}
iframe {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<h2>我是父级页面</h2>
<button id='btn'>父页面的按钮</button>
<div id="default">div内容</div>
<iframe src="http://localhost:8800/child.html" frameborder="0" name='myframe' id='myframe'></iframe>
<script language="javascript" type="text/javascript">
window.addEventListener('message',function(e){
console.log(e.data);
if(e.data.msg==='hideselfService'){
document.getElementById('default').style.display = 'none';
}
});
document.getElementById('btn').onclick= function(){
var myframe = document.getElementById('myframe');
myframe.contentWindow.postMessage({data:'parent'},'http://localhost:8800');
}
</script>
</body>
</html>
child.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iframe子页面</title>
</head>
<body>
<h2>我是内嵌的子页面</h2>
<button id='btn'>子页面的按钮</button>
<script>
document.getElementById('btn').onclick= function(){
window.parent.postMessage({
msg:"hideselfService"
},'*');
}
window.addEventListener('message', function(e){
console.log(e.data.data);
})
</script>
</body>
</html>
tips:测试后的时候,我是分别用node起了两个服务,父页面在localhost:8000上,子页面在localhost:8800上