估计很少人知道HTML5 APIS里有一个window.postMessage API。window.postMessage的功能是允许程序员跨域在两个窗口/frames间发送数据信息。基本上,它就像是跨域的AJAX,但不是浏览器跟服务器之间交互,而是在两个客户端之间通信。让我们来看一下window.postMessage是如何工作的。除了IE6、IE7之外的所有浏览器都支持这个功能。
数据发送端
首先我们要做的是创建通信发起端,也就是数据源”source”。作为发起端,我们可以open一个新窗口,或创建一个iframe,往新窗口里发送数据,简单起见,我们每6秒钟发送一次,然后创建消息监听器,从目标窗口监听它反馈的信息。JavaScript Code复制内容到剪贴板//弹出一个新窗口
vardomain ="http://scriptandstyle.com";
varmyPopup = window.open(domain
+"/windowPostMessageListener.html","myWindow");
//周期性的发送消息
setInterval(function(){
varmessage ="Hello! The time is: "+ (newDate().getTime());
console.log("blog.local: sending message: "+ message);
//send the message and target URI
myPopup.postMessage(message,domain);
},6000);