Is there a way to retrieve from within my Google Chrome extension the list of all available translations?
For instance, my app may contain the following folders:
_locales\en\messages.json
_locales\fr\messages.json
_locales\es\messages.json
Is there a way to know that it's en
, fr
, and es
from within the extension itself?
And a second question, is there any way to parse a specific messages.json
file as the JSON data? I mean a little bit more capabilities than what's provided by chrome.i18n.getMessage()
.
Is there a way to retrieve from within my Google Chrome extension the list of all available translations?
For instance, my app may contain the following folders:
_locales\en\messages.json
_locales\fr\messages.json
_locales\es\messages.json
Is there a way to know that it's en
, fr
, and es
from within the extension itself?
And a second question, is there any way to parse a specific messages.json
file as the JSON data? I mean a little bit more capabilities than what's provided by chrome.i18n.getMessage()
.
2 Answers
Reset to default 5Yes to both questions, thanks to the ability to read the extension's own folder:
chrome.runtime.getPackageDirectoryEntry(function callback)
Returns a
DirectoryEntry
for the package directory.
For example, you can list locales in this way (not resilient, add your own error checks):
function getLocales(callback) {
chrome.runtime.getPackageDirectoryEntry(function(root) {
root.getDirectory("_locales", {create: false}, function(localesdir) {
var reader = localesdir.createReader();
// Assumes that there are fewer than 100 locales; otherwise see DirectoryReader docs
reader.readEntries(function(results) {
callback(results.map(function(de){return de.name;}).sort());
});
});
});
}
getLocales(function(data){console.log(data);});
Likewise, you can use this to obtain a FileEntry for the messages.json file and parse it.
Edit: or you can use XHR as described in Marco's answer once you know the folder name.
To know what is the current locale used by the user, you can do this:
currentLocale = chrome.i18n.getMessage("@@ui_locale");
Now currentLocale
will be something like "en"
or "fr"
or wathever is the locale used by the user. So now you can use it to build locale-specific URLs.
To use your messages.json
as a Javascript Object you can:
- Get the current locale
- Request the
messages.json
file with anXMLHttpRequest
- Parse the content into an object using the
JSON.parse()
method.
Let's say you've got a messages.json
file like this:
{
"hello": {
"message": "Hello world!",
"description": "Sample text used for testing."
}
}
You will now do an XHR to get the file, something like this:
var currentLocale = chrome.i18n.getMessage("@@ui_locale"),
xhr = new XMLHttpRequest(),
messages;
xhr.open("GET", "/_locales/"+currentLocale+"messages.json", false);
xhr.send();
messages = JSON.parse(xhr.responseText);
// now you can access the messages like this:
alert(messages["hello"].message);
And you'll see your message alert.