父:<!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>