Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@developit
Created January 9, 2019 21:00
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 developit/8bcde6c734724653299d382b32a4e36c to your computer and use it in GitHub Desktop.
Save developit/8bcde6c734724653299d382b32a4e36c to your computer and use it in GitHub Desktop.
A polyfill for CORS in older versions of IE.
var xhr2 = false;
try { xhr2 = 'useCredentials' in new XMLHttpRequest; } catch (e) {}
var old = window.XMLHttpRequest;
function XMLHttpRequest() {
if (xhr2) return new old();
}
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
var pageOrigin = location.protocol + ':' + location.host;
var self = this;
function wrap(m) {
xhr[m] = function() {
for (var i in xhr) if (typeof xhr[i] !== 'function') {
try { self[i] = xhr[i]; } catch (e) {}
}
if (fn) fn();
if (self[m]) self[m].apply(self, arguments);
};
}
var xhr;
if (url && /^https?:\/\//i.test(url) && url.indexOf(host)!==0 && self.XDomainRequest) {
xhr = new XDomainRequest();
wrap('onload', function() {
self.readyState = 4;
if (self.onreadystatechange) self.onreadystatechange();
});
wrap('onerror', function() {
self.readyState = 4;
if (self.onreadystatechange) self.onreadystatechange();
});
}
else {
xhr = new old();
wrap('onreadystatechange', function() {
if (xhr.readyState===4) {
if (xhr.status && xhr.status <400 && xhr.status >= 200) {
if (self.onload) self.onload();
}
else if (self.onerror) self.onerror(Error(0));
}
};
}
this._xhr = xhr;
xhr.timeout = self.timeout;
wrap('onprogress');
wrap('ontimeout');
xhr.open(method, url, async, user, pass);
};
XMLHttpRequest.prototype.abort = function(){
this._xhr.abort();
};
XMLHttpRequest.prototype.getAllResponseHeaders = function() {
try { return this._xhr.getAllResponseHeaders(); } catch (e) {}
};
XMLHttpRequest.prototype.getResponseHeaders = function() {
try { return this._xhr.getResponseHeaders(); } catch (e) {}
};
XMLHttpRequest.prototype.send = function() {
setTimeout(function (x) { x.send(); }, 0, this._xhr);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment