跨域资源共享 (CORS) 是一种允许在 Web 浏览器中从另一个域加载受限资源的机制
例如,假设我们在 HTML5 演示部分单击 HTML5 视频播放器。首先,它会询问相机权限,如果用户允许权限,那么只有它会打开相机,否则不会。
提出 CORS 请求
Chrome、Firefox、Opera 和 Safari 等现代浏览器都使用 XMLHttprequest2 对象,而 Internet Explorer 使用类似的 XDomainRequest 对象。
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
}
else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
CORS 中的事件句柄
事件处理程序 | 描述 |
---|---|
onloadstart |
启动请求 |
onprogress |
加载数据并发送数据 |
onabort |
中止请求 |
onerror |
请求失败 |
onload |
请求加载成功 |
ontimeout |
在请求完成之前已超时 |
onloadend |
当请求完成时,成功或失败 |
onload 或 onerror 事件的示例
xhr.onload = function() {
var responseText = xhr.responseText;
// process the response.
console.log(responseText);
};
xhr.onerror = function() {
console.log('There was an error!');
};
带有处理程序的 CORS 示例
下面的示例将显示 makeCorsRequest() 和 onload 处理程序的示例
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'http://www.qikepu.com';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}