Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a list of available locale translations from my Chrome extension?

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().

like image 341
c00000fd Avatar asked Oct 23 '25 12:10

c00000fd


1 Answers

Yes 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.

like image 146
Xan Avatar answered Oct 25 '25 02:10

Xan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!