Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

javascript - 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:

_localesenmessages.json
_localesfrmessages.json
_localesesmessages.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().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...