iframe父子页面通信

同于域名下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”,则只有父页面在此源下才能接收到这个数据,“ * ”则代表任易都能接收到这个数据

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值