html5如何实现跨文档消息传输?
首先,要是想接受从其他的窗口那里发送的消息,就必须对窗口对象的message事件进行监视。代码如下
window.addEventListener("message",function(){},false)
使用window对象的postMessage方法向其他窗口发送消息,其方法定义如下
otherWindow.postMessage(message,targetOrigin)
该方法第一个参数为所发送的消息文本
该方法第二个参数接收消息的URL地址
//1.html
<!DOCTYPE html>
<html><head>
<meta charset="UTF-8">
<title></title>
<script>
window.onload=function(){
document.getElementById('title').innerHTML='页面在'+document.location.host+'域中,且每过1秒向跨文档消息传输2.html发送一个消息!';
//定时向另外一个不确定域的文件发送消息
setInterval(function(){
var message='消息发送测试! '+(new Date().getTime());
// document.write(message);
window.parent.frames[0].postMessage(message,'*');//message为要发送的消息,*表示可以传递给任意的窗口
},1000);
}
</script>
</head>
<body>
<div id="title"></div>
</body>
</html>
//2.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
window.onload=function(){
var onmessage=function(e){
var data=e.data,
p=document.createElement('p');
p.innerHTML=data;
document.getElementById('display').appendChild(p);
};
//监听postMessage消息事件
if(typeof window.addEventListener!='undefined'){
window.addEventListener('message',onmessage,false);//接收到message消息调用onmessage函数
}
else if(typeof window.attachEvent!='undefined')
{
window.attachEvent('onmessage',onmessage);
}
};
</script>
</head>
<body>
<div id="display()"></div>
</body>
</html>
1.html显示效果如下: