iframe跨域通信--html5.postmessage

父:<!doctype html>

<html>

<head>

    <meta charset="utf-8"/>

    <title>跨域测试</title>

</head>

<body>

<script>

 if (typeof window.postMessage != 'undefined'){// 检查浏览器是否支持postMessage

 var iframe = document.createElement('iframe');

 iframe.src = 'http://login2.qingdao.gov.cn/uc/iframe1.html';

 document.body.appendChild(iframe);

 var reciever = function(e) {监听到事件之后的回调

 debugger;

      var data = e.data;

      alert(data);

   };

 if (window.addEventListener){//兼容监听绑定事件---addEventListener:不带on

     window.addEventListener('message', reciever, false);

 }else if (window.attachEvent){

     window.attachEvent('onmessage', reciever);

 }

    }

</script>

</body>

</html>

 

子:<!doctype html>

<html>

<head>

    <meta charset="utf-8"/>

    <title></title>

</head>

<body>

<script>

 if (typeof window.postMessage != 'undefined') {// 检查浏览器是否支持postMessage

 setInterval(function(){

 var message="nihao";

 window.parent.postMessage(message, '*');//注意向父窗口发送消息,如果往本页面的iframe发消息,需要指明哪个iframe.contentWindow.postMessage

 },1000);

}

/*

通过调用目标页面window对象中的postMessage()函数可发送消息,代码如下:

window.parent.postMessage(“Hello, world”, “portal.example.com”);

第一个参数包含要发送的数据,第二个参数是消息传送的目的地。

注意:要发送消息给iframe,可以在相应iframe的contentWindow,中调用 postMessage,代码如下:

document.getElementsByTagName(“iframe”)[0].contentWindow.postMessage(“Hello, world”, “url”);例如iframe2

*/

</script>

</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值