Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery CORS Plugin - transparently add CORS support for IE8+ in jQuery using XDomainRequest. Support cookies.
(function($) {
var urlParseRE = /^(((([^:\/#\?]+:)?(?:\/\/((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?]+)(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/;
function parseUrl(url) {
if (typeof url === "object") {
return url;
}
var u = url || "", matches = urlParseRE.exec(url), results;
if (matches) {
results = {
href: matches[0] || "",
hrefNoHash: matches[1] || "",
hrefNoSearch: matches[2] || "",
domain: matches[3] || "",
protocol: matches[4] || "",
authority: matches[5] || "",
username: matches[7] || "",
password: matches[8] || "",
host: matches[9] || "",
hostname: matches[10] || "",
port: matches[11] || "",
pathname: matches[12] || "",
directory: matches[13] || "",
filename: matches[14] || "",
search: matches[15] || "",
hash: matches[16] || ""
};
}
return results || {};
}
function createXDR() {
try {
var xdr = new window.XDomainRequest();
if (!xdr.setRequestHeader) {
xdr.setRequestHeader = $.noop;
}
if (!xdr.getAllResponseHeaders) {
xdr.getAllResponseHeaders = $.noop;
}
xdr.onload = function() {
setTimeout(function(){
if (typeof xdr.onreadystatechange === 'function') {
xdr.readyState = 4;
xdr.status = 200;
xdr.onreadystatechange.call(xdr, null, false);
}
}, 0);
};
xdr.onerror = xdr.ontimeout = function() {
setTimeout(function(){
if (typeof xdr.onreadystatechange === 'function') {
xdr.readyState = 4;
xdr.status = 500;
xdr.onreadystatechange.call(xdr, null, false);
}
}, 0);
};
return xdr;
} catch(e) {
}
}
if(!$.ajaxSettings.oldXhr) {
$.ajaxSettings.oldXhr = $.ajaxSettings.xhr;
}
if ($.browser.msie && window.XDomainRequest) {
$.support.cors = true;
$.ajaxSettings.xhr = function() {
var domain = parseUrl(this.url).domain;
return domain === "" || domain === parseUrl(document.location.href).domain ?
$.ajaxSettings.oldXhr() :
createXDR();
};
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.