views:

12

answers:

1

Let's say I have a JSON file stored within my extension called settings.json. I can get the URL of the file using chrome.extension.getURL("settings.json");

But now that I have the URL, how do I actually load the contents of that file so I can JSON.parse it and use it? The reason I'm doing this is that there is a server component, and I want to make deployment and testing on multiple servers easier (dev, staging, production, etc.) Alternatively if there's a way to add custom attributes to the manifest.json and access them, that would also work.

A: 

If you make your setting.js look like:

var settings =  {"param":value,...};

Then you can just include it on a background page and use settings variable:

<script src="settings.js"></script>

If you want to have pure json in your file without assigning it to any variables then you can load it using XMLHttpRequest:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange; // Implemented elsewhere.
xhr.open("GET", chrome.extension.getURL('/config_resources/config.json'), true);
xhr.send();

or if you included jquery into your project:

$.getJSON(chrome.extension.getURL('/config_resources/config.json'), function(settings) {
  //..
});

(btw using chrome.extension.getURL is required only if you are accessing a file from a content script, otherwise you can just use relative path /config_resources/config.json)

serg
I may end up doing your first suggestion. With the second, I get the following error (from within a content script): XMLHttpRequest cannot load chrome-extension://<APPID>/settings.json. Cross origin requests are only supported for HTTP.Uncaught Error: NETWORK_ERR: XMLHttpRequest Exception 101
Evan
@Evan Ok then I was wrong about content script, sorry. If you need it in a content script you can send a request to background page using `chrome.extension.sendRequest` and ask it to get settings for you (you will need to send a request in any case, even with first method).
serg

related questions