HTML5提供了跨文档消息机制(Cross Document Messaging),它提供了跨越frame、tabs或windows通信的能力。
PostMessage API
要接收消息的页面需要添加相应的事件监听器,在消息到来时你可以检测其来源来并判断是否处理。
浏览器的支持情况:
检测浏览器支持:
JavaScript Code复制内容到剪贴板
if (typeof window.postMessage === “undefined”) {
// postMessage not supported in this browser
}
发送消息:
发送消息给另一个页面:
JavaScript Code复制内容到剪贴板
window.postMessage(“Hello, world”, “portal.example.com”);
发送消息给iframe:
JavaScript Code复制内容到剪贴板
document.getElementsByTagName(“iframe”)[0].contentWindow.postMessage(“Hello, world”,
“chat.example.net”);
监听消息:
首先设置白名单,对接受到的消息进行过滤,只处理信任页面发送的消息。
JavaScript Code复制内容到剪贴板
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。
浏览器支持情况:
检测浏览器支持:
JavaScript Code复制内容到剪贴板
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";
}
执行跨域请求:
var crossOriginRequest = new XMLHttpRequest()
crossOriginRequest.open(“GET”, “http://www.example.net/stockfeed”, true);
使用进度通知事件:
JavaScript Code复制内容到剪贴板
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
}
}
转载请注明:睿美印象
网站建设工作室www.ruimeiyx.com