版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BuFanQi_Info/article/details/81480522
同于域名下iframe父子页面通信
方法调用
父页面调用子页面方法:FrameName.window.childMethod();
子页面调用父页面方法:parent.window.parentMethod();
- parent.html
<html>
<head>
<script type="text/javascript">
function say() {
alert("parent.html------>I'm at parent.html");
}
function callChild()
{
myFrame.window.say();
}
</script>
</head>
<body>
<input type=button value="调用child.html中的函数say()" onclick="callChild()">
<iframe name="myFrame" src="child.html"></iframe>
</body>
</html>
- child.html
<html>
<head>
<script type="text/javascript">
function say()
{
alert("child.html--->I'm at child.html");
}
function callParent() {
parent.say();
}
</script>
</head>
<body>
<input id="button" type=button value="调用parent.html中的say()函数" onclick="callParent()">
</body>
</html>
跨域下iframe父子页面通信
- parent 父页面
此为消息监听e.data为postMessage传来的参数,默认为’ubaLoadDone’
window.addEventListener('message', function(e){
console.log('bar say1111: '+e.data);
if(e.data != undefined && e.data !='ubaLoadDone'){
window.location.href=e.data.adress;
}
}, false);
- child 子页面
var post= {"adress":"xxxxxx"};
window.parent.postMessage(post,'*');
postMessage的参数
第一个: post为需要传的参数,可以为字符串,也可以为对象
第二个:通知给哪个源下面的资源,比如“http://www.baidu.com”,则只有父页面在此源下才能接收到这个数据,“ * ”则代表任易都能接收到这个数据