HTML5 规范中,提出了XDM,又称为 跨文档消息传递,其核心是 postMessage()方法,进行跨域和跨文档消息传递,示例如下:
<div class="CrossDocumentMessage"> Cross Document Message , core---->postMessage()</div> <iframe id="frame_corssDM" src="http://localhost:63342/XDM.html"> postMessage() 方法 </iframe>
假设该页面的访问地址为:http://localhost:63342/XDM1.html
与该页面进行消息传递的页面为:http://localhost:63342/XDM.html(即<iframe>的sr)
这时需要添加JavaScript脚本:首先在http://localhost:63342/XDM1.html 页面(当前页面)添加js 如下:
var Ele_frame= document.getElementById('frame_corssDM').contentWindow; Ele_frame.postMessage('getcolor','http://localhost:63342/');//(参数一是 要发送的字符串,参数二是 消息接收者所在的域的 字符串形式)
接下来在消息接收页面添加js ,由于 接收XDM消息时,会触发 window 对象的 message 事件,所以......
window.addEventListener('message',function(event){
if(event.origin=="http://localhost:63342"){ //确保消息是发送方是 我们知道的
var color=document.getElementById('canvasImg').style.backgroundColor;
window.parent.postMessage(color,'http://localhost:63342');
}
},false);
我们将消息从当前页面(http://localhost:63342/XDM1.html)发送至消息接收方(http://localhost:63342/XDM.html),之后消息接收方又给当前页面发送一条消息,此时只要在当前页面 添加如下代码......
window.addEventListener('message',function(event){ var Ele_CDM=document.getElementsByClassName('CrossDocumentMessage')[0]; Ele_CDM.innerHTML=event.data; },false);
就可将接收到的回显数据添加至页面