如何使用Chrome.i18n Web扩展API检索消息的内容。
使用Chrome的Chrome.i18n
API时,chrome.i18n.getMessage
方法一次仅检索一条消息。
const buttonText = chrome.i18n.getMessage('buttonText');
我想要的是在弹出窗口打开message.json
文件的本地内容时更新弹出式UI。这样做需要我知道使用的消息名称。是否有类似于getMessage
的方法/技术,用于一次检索Message.json
文件的所有内容?
现在,我只能将所有消息名称保留在某个地方,并单独检索每个本地化消息,例如:
const messages = ["buttonText", "buttonTitle"];
messages.forEach((message) => {
const messageText = chrome.i18n.getMessage(message);
// Update UI
});
When using chrome's chrome.i18n
API, the chrome.i18n.getMessage
method retrieves only one message at a time.
const buttonText = chrome.i18n.getMessage('buttonText');
What I want is to update the popup UI when the popup opens with the localized contents of message.json
file. Doing so requires me to know the message names used. Is there a method/technique similar to getMessage
for retrieving all the contents of the message.json
file at once?
Right now, I can only keep all the message names somewhere and retrieve each localized message individually like:
const messages = ["buttonText", "buttonTitle"];
messages.forEach((message) => {
const messageText = chrome.i18n.getMessage(message);
// Update UI
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要获取“ messages.json”文件,您必须使用“ fetch”并使用” chrome.runtime“ API和“ geturl”方法。
唯一的事情是,以这种方式,您必须自己指定语言并验证它,这就是我的做法:
检测浏览器的语言,并验证它是否存在于我的扩展中,除了默认语言外,在这种情况下,在这种情况下是英语,如果数组中不存在它,则不会修改并默认保留。
我的“ _locales”目录:
_locales-> en->消息
_locales-> es->消息
最终,要迭代“ message.json”的结果,因为它是一个对象,我找到了这些方法:
两种方式迭代并返回给定对象的键。更多信息:与对象一起工作。
最终代码:这将返回JSON主对象中每个对象的“消息”键的每个值。
文件“ _locales - > en - > messages.json”:
控制台中的结果将是:
Sorry if the wording is not correct or I am very repetitive, I had to use the translator.
To get the "messages.json" file you would have to use "fetch" and access the URL of the file with the "chrome.runtime" API and the "getURL" method.
The only thing is that in this way you have to specify the language yourself and verify it, that's how I did it:
Detecting the language of the browser and verifying if it exists in my extension apart from the default language, in this case English, if it does not exist in the array it is not modified and remains by default.
My "_locales" directory:
_locales -> en -> messages.json
_locales -> es -> messages.json
Finally, to iterate the result of "messages.json", as it is an object, I found these ways:
Both ways iterate and return the keys of the given object. more info: Working with objects.
Final code: this will return each value of the "message" key of each object within the main object of the json.
The file "_locales -> en -> messages.json":
The result in the console will be something like:
Sorry if the wording is not correct or I am very repetitive, I had to use the translator.