vibog vibog - 4 months ago 78
Ajax Question

AJAX request to local file system not working in Chrome?

I am working to dynamically create a UI from XML using jQuery. My jQuery is working in Firefox but in Chrome it's not working. It gives me this console error:


Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.


The following is my jQuery code which working on Firefox but not working on Google chrome:

$.ajax({
url: 'file:///home/satendra/dndExamples/avisDnD/file.xml',
success: function(xml) {
$(xml).find('Tab').each(function() {
var id = $(this).attr('URL');
var tab = $(this).attr('TabName');
$("ul").append("<li><a href="+ id +">"+ tab +"</li>");
});
}
});

Answer

Firefox allows the request because it accepts requests to the local file system (ie. the file:// protocol) if they originate from there too. However Chrome denies all XMLHttpRequests to file:// urls.

Note that you cannot make an AJAX request to the local file system from an external domain in either browser - it would be a massive security flaw if you could.

For this AJAX request to work in Chrome you need to make the request to a webserver. If you're on Windows you can easily install IIS or WAMP on your local machine.

Note that it is possible to enable a setting in Google Chrome which allows requests to the local file system from the browser, but it's really not a good idea to use it. If you decide you want to go ahead and do this anyway, a guide can be found here.