我可以从我的Chrome扩展中获得可用的区域设置翻译列表吗

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

本文关键字:区域 设置 翻译 列表 我的 Chrome 扩展 我可以      更新时间:2023-09-26

有没有办法从我的Google Chrome扩展中检索所有可用翻译的列表?

例如,我的应用程序可能包含以下文件夹:

_locales'en'messages.json
_locales'fr'messages.json
_locales'es'messages.json

有没有办法从扩展本身中知道它是enfres

第二个问题是,有没有办法将特定的messages.json文件解析为JSON数据?我的意思是比chrome.i18n.getMessage()提供的功能多一点。

这两个问题都是,这要归功于能够读取扩展自己的文件夹:

chrome.runtime.getPackageDirectoryEntry(function callback)

返回包目录的DirectoryEntry

例如,您可以用这种方式列出区域设置(不具有弹性,添加您自己的错误检查):

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);});

同样,您可以使用它来获取messages.json文件的FileEntry并对其进行解析。
编辑:或者,一旦您知道文件夹名称,您就可以按照Marco的回答使用XHR。

要知道用户当前使用的语言环境是什么,可以执行以下操作:

currentLocale = chrome.i18n.getMessage("@@ui_locale");

现在currentLocale将类似于"en""fr",或者wathever是用户使用的语言环境。因此,现在您可以使用它来构建特定于区域设置的URL。

要将messages.json用作Javascript对象,您可以:

  1. 获取当前区域设置
  2. 使用XMLHttpRequest请求messages.json文件
  3. 使用JSON.parse()方法将内容解析为对象

假设您有一个messages.json文件,如下所示:

{
    "hello": {
         "message": "Hello world!",
         "description": "Sample text used for testing."
    }
}

您现在将执行XHR来获取文件,类似于以下内容:

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);

您将看到您的消息提醒。