我可以从我的 Chrome 扩展程序中获取可用的语言环境翻译列表吗?
有没有办法从我的 Google Chrome 扩展程序中检索所有可用翻译的列表?
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
有没有办法从扩展本身中知道它是 en
、fr
和 es
?
Is there a way to know that it's en
, fr
, and es
from within the extension itself?
第二个问题,有没有办法将特定的 messages.json
文件解析为 JSON 数据?我的意思是比 chrome.i18n.getMessage()
提供的功能多一点.
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(函数回调)
返回包目录的 DirectoryEntry
.
例如,您可以以这种方式列出语言环境(没有弹性,添加您自己的错误检查):
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);});
同样,您可以使用它来获取 messages.json 文件的 FileEntry 并解析它.
或者您可以按照 Marco's answer 中所述使用 XHR,一旦您知道文件夹名称.
Likewise, you can use this to obtain a FileEntry for the messages.json file and parse it.
or you can use XHR as described in Marco's answer once you know the folder name.
相关文章