During the development and testing stages of a new website, there are time when you may need to access Json or xml data stored in a local file. The test site can be running under Visual Studio, IIS Express or even IIS. I recently had to quickly test some javascript code that interacted with Json data. I was trying to debug using Chrome's Developers tools but I was getting an error at every execution.
The method was doing nothing more than this:
$.getJSON('file:///C:/Temp/testdata.json'
By default, Chrome does not allow javascript to interact with local file systems. If you try, then you will be greeted with the following error message:
XMLHttpRequest cannot load file:///C:/path/to/C:/Temp/testdata.json. Origin null is not allowed by Access-Control-Allow-Origin.
However, Chrome offers a flag that lets you turn on this feature as described below (please note that the steps are for Windows 7-8 but the same logic applies to Mac OS X)
- Close down your Chrome browser (make sure you close all instances if you have multiple windows open)
- Go to Run and type the following command:
chrome.exe --allow-file-access-from-file - Hit enter
For all you Mac fun boys out there (me included as I'm typing this on my Mac Book Pro Retina) the command equivalent for step 2 is:
Run Terminal.app Type "open /Applications/Google\ Chrome.app --args --allow-file-access-from-file", no quotes.
Now you should be able to do the following in your code (snippet below)
$(document).ready(function() {
var items = [];
$.getJSON('file:///C:/Temp/testdata.json', .. rest of the code here
Happy Coding...