参考地址 postMessage父子跨域通信
1.子向父通信
parent.html
window.addEventListener('message',function(e){ console.log(e.data); if(e.data.msg==='xxx'){ //一些自己的业务逻辑 }});
child.html
window.parent.postMessage({ msg:"xxx"},'*');
2.父向子通信
parent.html
var myframe = document.getElementById('myframe');//获取iframemyframe.contentWindow.postMessage({data:'parent'},childDomain);//childDomain是子页面的源(协议+主机+端口号)
child.html
window.addEventListener('message', function(e){ console.log(e.data.data);})
注意:
1.子向父,子postMessage,父监听message;
2.父向子,父postMessage,子监听message;
3.测试发现,子向父postMessage的时候,源可以写为‘*’,父向子postMessage的时候,源需要写成子的源,(也就是子页面的协议+主机号+端口)
测试代码部分:
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上