代码改变世界

HTML5之PostMessage

2011-06-01 14:27  卫佳  阅读(470)  评论(0编辑  收藏  举报

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

浏览器的支持情况:

检测浏览器支持:

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”);

监听消息mbt tembea womens shoes wholesale

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

    var originWhiteList = [“portal.example.com”, “games.example.com”, “www.example.com”]; 
    function checkWhiteList(origin) { 
        for (var i=0; i<originWhiteList.length; i++) { 
            if (origin === originWhiteList[i]) { 
            return true; 
            } 
        } 
        return false; 
    } 
    function messageHandler(e) { 
        if(checkWhiteList(e.origin)) { 
            processMessage(e.data); 
        } else { 
        // ignore messages from unrecognized origins 
        } 
    } 
    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。

浏览器支持情况:

检测浏览器支持:

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

执行跨域请求2011 mbt fanaka men's shoes

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

使用进度通知事件:

  crossOriginRequest.onprogress = function(e) { 
    var total = e.total; 
    var loaded = e.loaded; 
    if (e.lengthComputable) { 
    // do something with the progress information 
    } 
    } 
    crossOriginRequest.upload.onprogress = function(e) { 
    var total = e.total; 
    var loaded = e.loaded; 
    if (e.lengthComputable) { 
    // do something with the progress information 
    } 
    }