父向子通信
A.html
var myframe = document.getElementById('myframe');//获取iframe
myframe.contentWindow.postMessage({data:'parent'},'http://127.0.0.1:9999');//参数2是子页面的源(协议+主机+端口号)
B.htnl
window.addEventListener('message', function(e){
//e 包含父页面床来的数据
console.log(e.data.data);
})
子向父通信
B.html
window.parent.postMessage({
msg:"xxx"
},'*');
A.html
window.addEventListener('message',function(e){
console.log(e.data);
if(e.data.msg==='xxx'){
//写业务逻辑的地方
}
});