Cross-origin resource sharing (CORS) là cơ chế cho phép tài nguyên bị hạn chế từ domain khác trong trình duyệt web.
Ví dụ, nếu bạn click vào trình phát video HTML5 trong phần demo. Nó sẽ xin quyền camera. Nếu người dùng cho phép thì mới mở camera, ngược lại không mở cho ứng dụng web.
Chrome, Firefox, Opera, Safari dùng đối tượng XMLHttprequest2, Internet Explorer dùng XDomainRequest tương tự.
function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // Kiểm tra xem XMLHttpRequest có thuộc tính "withCredentials" không. // "withCredentials" chỉ tồn tại trên XMLHTTPRequest2. xhr.open(method, url, true); } else if (typeof XDomainRequest != "undefined") { // Nếu không, kiểm tra XDomainRequest. // XDomainRequest chỉ tồn tại trong IE, là cách IE làm CORS. xhr = new XDomainRequest(); xhr.open(method, url); } else { // Ngược lại, CORS không được hỗ trợ bởi trình duyệt. xhr = null; } return xhr; } var xhr = createCORSRequest('GET', url); if (!xhr) { throw new Error('CORS not supported'); }