Created
January 9, 2019 21:00
-
-
Save developit/8bcde6c734724653299d382b32a4e36c to your computer and use it in GitHub Desktop.
A polyfill for CORS in older versions of IE.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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