Skip to content

Instantly share code, notes, and snippets.

@warpech
Forked from mathieucarbou/jquery.xdomain.js
Created December 15, 2011 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warpech/1481661 to your computer and use it in GitHub Desktop.
Save warpech/1481661 to your computer and use it in GitHub Desktop.
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