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().
Yes to both questions, thanks to the ability to read the extension's own folder:
chrome.runtime.getPackageDirectoryEntry(function callback)Returns a
DirectoryEntryfor 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With