In order to add multilingual support to your WebExtension, you need to add localized messages to _locales/*/messages.json
files (*
is a language code id). This allows to get a localized message using the i18n API by referencing your keys like so __MSG_MessageKey__
.
Unless I didn’t miss something, the current multilingual support is somewhat limited. As described in https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Internationalization you can auto-translate text inside your manifest.json (this works) and css files (didn’t try that myself). Unfortunately, loading HTML files as sidebar pages, page action popups, browser action popups, … won’t auto-replace message keys within them.
– Please let me know if that is supposed to work or not
One way to have such localized pages could be to load a generic page that contains no localized text, but message keys and then search-and-replace these once the page is loaded; i.e. potentially lots of calls to i18n.getMessage(“MessageKey”).
Another way could be to place already localized pages inside the _locales/*
folders and load the right version as needed. The problem with this approach is, that there does not seem to be a safe way to determine from which folder to load the localized resource; i.e. which language code do you have to use when calling browser.runtime.getURL(_locales/*/some.resource
)?
i18n.getUILanguage() might trick you into using it to answer that question. The issue is, that your WebExtension could have a _locales/en
folder, but no _locales/en_US
folder and still get “en_US” as result. So getUILanguage()'s result might only be useful to construct URLs for external sites. The same applies to i18n.getMessage(@@ui_locale
), which seems to be functionally equivalent to .getUILanguage().
The only workaround seems to be to add a (AddonLocale: “en”) message definition to the _locale/en/messages.json
file and similar ones to all the others. This allows to use .getMessage(“AddonLocale”) to determine the location of a localized resource. That approach is of course error prone as the actual message must always correspond to the name of the parent folder.
So i18n could use a function that allows a WebExtension to detect from which folder to load a localized resource. A i18n.getAddonLanguage() function could return “en” as result if a WebExtension has a _locales/en
folder and if _locales/en/messages.json
is the current message file in use.