Read file:// URLs in IE XMLHttpRequest
Hmm, could it be the difference between the native XMLHttpRequest object and the ActiveX one? I seem to remember something about that. That is, instead of
var xhr = new XMLHttpRequest();
try
var xhr = new ActiveXObject("MSXML2.XMLHTTP");
Obviously, put some checks in place to see if the browser supports ActiveX. Of course, this is limited to IE only, as well.
How can I get code like this to work?
As suggested above, this looks like a fault in Microsoft XMLHttpRequest
. jQuery (Jul 2011) also writes:-
Microsoft failed to properly implement the XMLHttpRequest in IE7 (can't request local files)
I confirm this failure for IE8 too.
A solution is to use new window.ActiveXObject( "Microsoft.XMLHTTP" )
for local files if XMLHttpRequest
doesn't work.
The failure is in the xhr.open
line so it can be caught there and then try ActiveXObject
as follows:-
var xhr = new XMLHttpRequest()try { xhr.open('GET', url, true)}catch(e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP') xhr.open('GET', url, true) } catch (e1) { throw new Error("Exception during GET request: " + e1) }}
This code will at least use standard XMLHttpRequest
for IE9 (untested) and future IE browsers if/when Microsoft fixes the fault. With the jQuery
code above, non standard Microsoft.XMLHTTP
will be used whenever ActiveXObject
is available, even if Microsoft fix the fault.
I just happened to stumble across exactly the same problem. As suggested above, the non-native ActiveX "constructor" works. I’m not really sure whether there are different policies applied to the two objects, but since jQuery mentions the same problem as well, it may be a genuine bug. Here is the relevant piece of code from the jQuery source (1.4.2, line 4948):
// Create the request object; Microsoft failed to properly// implement the XMLHttpRequest in IE7 (can't request local files),// so we use the ActiveXObject when it is available// This function can be overriden by calling jQuery.ajaxSetupxhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ? function() { return new window.XMLHttpRequest(); } : function() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} }