leonheess
leonheess

Reputation: 21381

Loading an local JSON file offline

So I have a client that wants a site that is not hosted anywhere but locally accessible via a browser (a html file in a folder). Now the tricky part is that they want to change this site on their own IN the browser. So I thought the best way to do this is to have a config locally. I created a config.json and went on to get it:

$.getJSON("config.json", function(config){
    //use config to alter the site
});

I found out here that modern browsers however block this kind of requests since it is considered unsafe. For example Chrome says:

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

Now the question is: How can I have a file that stores my config so that Javascript/jQuery can load it. Is there a way to ask the user to allow the fileaccess? Is there a completely different way of doing all this that suits the task better?

I'm looking forward to any suggestion as long as it is offline-compatible!

Upvotes: 2

Views: 1628

Answers (1)

Jaromanda X
Jaromanda X

Reputation: 1

simplest solution: rename config.json to config.js for consistency

now, if the JSON is

{
    "configKey1": "value1"
}

wrap the json in a function,

function getconfig() { 
    return {
        "configKey1": "value1"
    };
}

now, simply have <script src="config.js"> in your HTML

then, when you want to get config ... call getconfig to read it

let config = getconfig();

Upvotes: 5

Related Questions