HTML5高级程序设计电子版--缺失篇--Communication API

HTML5提供了跨文档消息机制(Cross Document Messaging),它提供了跨越frame、tabs或windows通信的能力。

PostMessage API

要接收消息的页面需要添加相应的事件监听器,在消息到来时你可以检测其来源来并判断是否处理。

浏览器的支持情况:

浏览器支持

检测浏览器支持:

if (typeof window.postMessage === “undefined”) {
  // postMessage not supported in this browser
}

发送消息:

发送消息给另一个页面:
window.postMessage(“Hello, world”, “portal.example.com”);

发送消息给iframe:
document.getElementsByTagName(“iframe”)[0].contentWindow.postMessage(“Hello, world”,
“chat.example.net”);

监听消息:

首先设置白名单,对接受到的消息进行过滤,只处理信任页面发送的消息。

 1 var originWhiteList = [“portal.example.com”, “games.example.com”, “www.example.com”];  
 2 function checkWhiteList(origin) {  
 3     for (var i=0; i<originWhiteList.length; i++) {  
 4         if (origin === originWhiteList[i]) {  
 5         return true;  
 6         }  
 7     }  
 8     return false;  
 9 }  
10 function messageHandler(e) {  
11     if(checkWhiteList(e.origin)) {  
12         processMessage(e.data);  
13     } else {  
14     // ignore messages from unrecognized origins  
15     }  
16 }  
17 window.addEventListener(“message”, messageHandler, true); 
 

XMLHttpRequest Level 2

HTML5中定义了XMLHttpRequest Level 2,它有两方面的增强:跨域通信,通信进度通知(progress events)

跨域通信:

XMLHttpRequest Level 2使用跨域资源共享Cross Origin Resource Sharing(CORS)来提供跨越多个域的通信。所有跨域的请求都有Origin消息头,它保存发起请求的域的信息。Origin被浏览器保护无法在代码中作出修改。Origin消息头和PostMessage消息事件中的origin本质上相同。Origin和传统的referer消息头不同的地方在于,referer是完整的URL,包括文档路径(path)。由于文档路径可能包含隐私信息,所以有时候为保护用户隐私,浏览器并不会发送referer消息头。但是只要可能,浏览器总是会发送Origin消息头。
CORS标准要求一个credentials的请求(a request with credentials)或非GET、POST的请求,一定要发送perflight选项给服务器,所以跨域通信可能需要支持CORS的服务器。

进度通知:

XMLHttpRequest Level2发送消息的时候除了传统的readyState之外,还提供了如下进度通知相关的事件:
loadstart、progress、abort、error、load、loadend。

浏览器支持情况:

浏览器支持

检测浏览器支持:

1 var xhr = new XMLHttpRequest()  
2 if (typeof xhr.withCredentials === undefined) {  
3   document.getElementById("support").innerHTML =  
4   "Your browser <strong>does not</strong> support cross-origin XMLHttpRequest";  
5 } else {  
6   document.getElementById("support").innerHTML =  
7   "Your browser <strong>does</strong>support cross-origin XMLHttpRequest";  
8 }  
 

执行跨域请求:

var crossOriginRequest = new XMLHttpRequest()
crossOriginRequest.open(“GET”, “http://www.example.net/stockfeed”, true);

使用进度通知事件:

 1 crossOriginRequest.onprogress = function(e) {  
 2   var total = e.total;  
 3   var loaded = e.loaded;  
 4   if (e.lengthComputable) {  
 5     // do something with the progress information  
 6   }  
 7 }  
 8 crossOriginRequest.upload.onprogress = function(e) {  
 9   var total = e.total;  
10   var loaded = e.loaded;  
11   if (e.lengthComputable) {  
12     // do something with the progress information  
13   }  
14 } 
 
posted @ 2012-08-22 15:57  无赖君子  阅读(515)  评论(0编辑  收藏  举报