The WebExtensions API has a rather handy module available for internationalizing extensions — i18n. In this article we'll explore its features and provide a practical example of how it works. The i18n system for extensions built using WebExtension APIs is similar to common JavaScript libraries for i18n such as i18n.js.
Note: The example extension featured in this article — notify-link-clicks-i18n — is available on GitHub. Follow along with the source code as you go through the sections below.
An internationalized extension can contain the same features as any other extension — background scripts, content scripts, etc. — but it also has some extra parts to allow it to switch between different locales. These are summarized in the following directory tree:
Let's explore each of the new features in turn — each of the below sections represents a step to follow when internationalizing your extension.
Note: You can look up language subtags using the Find tool on the Language subtag lookup page. Note that you need to search for the English name of the language.
Every i18n system requires the provision of strings translated into all the different locales you want to support. In extensions, these are contained within a directory called _locales
, placed inside the extension root. Each individual locale has its strings (referred to as messages) contained within a file called messages.json
, which is placed inside a subdirectory of _locales
, named using the language subtag for that locale's language.
Note that if the subtag includes a basic language plus a regional variant, then the language and variant are conventionally separated using a hyphen: for example, "en-US". However, in the directories under _locales
, the separator must be an underscore: "en_US".
So for example, in our sample app we have directories for "en" (English), "de" (German), "nl" (Dutch), and "ja" (Japanese). Each one of these has a messages.json
file inside it.
Let's now look at the structure of one of these files (_locales/en/messages.json):
{ "extensionName": { "message": "Notify link clicks i18n", "description": "Name of the extension." }, "extensionDescription": { "message": "Shows a notification when the user clicks on links.", "description": "Description of the extension." }, "notificationTitle": { "message": "Click notification", "description": "Title of the click notification." }, "notificationContent": { "message": "You clicked $URL$.", "description": "Tells the user which link they clicked.", "placeholders": { "url" : { "content" : "$1", "example" : "https://developer.mozilla.org" } } } }
This file is standard JSON — each one of its members is an object with a name, which contains a message
and a description
. All of these items are strings; $URL$
is a placeholder, which is replaced with a substring at the time the notificationContent
member is called by the extension. You'll learn how to do this in the Retrieving message strings from JavaScript section.
Note: You can find much more information about the contents of messages.json
files in our Locale-Specific Message reference.
There are a couple of different tasks to carry out to internationalize your manifest.json.
Your manifest.json includes strings that are displayed to the user, such as the extension's name and description. If you internationalize these strings and put the appropriate translations of them in messages.json, then the correct translation of the string will be displayed to the user, based on the current locale, like so.
To internationalize strings, specify them like this:
"name": "__MSG_extensionName__", "description": "__MSG_extensionDescription__",
Here, we are retrieving message strings dependant on the browser's locale, rather than just including static strings.
To call a message string like this, you need to specify it like this:
messages.json
, followed by__MSG_ + messageName + __
Another field you should specify in your manifest.json is default_locale:
"default_locale": "en"
This specifies a default locale to use if the extension doesn't include a localized string for the browser's current locale. Any message strings that are not available in the browser locale are taken from the default locale instead. There are some more details to be aware of in terms of how the browser selects strings — see Localized string selection.
Note that you can also retrieve localized strings from CSS files in the extension. For example, you might want to construct a locale-dependent CSS rule, like this:
header { background-image: url(../images/__MSG_extensionName__/header.png); }
This is useful, although you might be better off handling such a situation using Predefined messages.
So, you've got your message strings set up, and your manifest. Now you just need to start calling your message strings from JavaScript so your extension can talk the right language as much as possible. The actual i18n API is pretty simple, containing just four main methods:
i18n.getMessage()
most often — this is the method you use to retrieve a specific language string, as mentioned above. We'll see specific usage examples of this below.i18n.getAcceptLanguages()
and i18n.getUILanguage()
methods could be used if you needed to customize the UI depending on the locale — perhaps you might want to show preferences specific to the users' preferred languages higher up in a prefs list, or display cultural information relevant only to a certain language, or format displayed dates appropriately according to the browser locale.i18n.detectLanguage()
method could be used to detect the language of user-submitted content, and format it appropriately.In our notify-link-clicks-i18n example, the background script contains the following lines:
var title = browser.i18n.getMessage("notificationTitle"); var content = browser.i18n.getMessage("notificationContent", message.url);
The first one just retrieves the notificationTitle message
field from the available messages.json
file most appropriate for the browser's current locale. The second one is similar, but it is being passed a URL as a second parameter. What gives? This is how you specify the content to replace the $URL$
placeholder we see in the notificationContent message
field:
"notificationContent": { "message": "You clicked $URL$.", "description": "Tells the user which link they clicked.", "placeholders": { "url" : { "content" : "$1", "example" : "https://developer.mozilla.org" } } }
The "placeholders"
member defines all the placeholders, and where they are retrieved from. The "url"
placeholder specifies that its content is taken from $1, which is the first value given inside the second parameter of getMessage()
. Since the placeholder is called "url"
, we use $URL$
to call it inside the actual message string (so for "name"
you'd use $NAME$
, etc.) If you have multiple placeholders, you can provide them inside an array that is given to i18n.getMessage()
as the second parameter — [a, b, c]
will be available as $1
, $2
, and $3
, and so on, inside messages.json
.
Let's run through an example: the original notificationContent
message string in the en/messages.json
file is
You clicked $URL$.
Let's say the link clicked on points to https://developer.mozilla.org
. After the i18n.getMessage()
call, the contents of the second parameter are made available in messages.json as $1
, which replaces the $URL$
placeholder as defined in the "url"
placeholder. So the final message string is
You clicked https://developer.mozilla.org.
It is possible to insert your variables ($1
, $2
, $3
, etc.) directly into the message strings, for example we could rewrite the above "notificationContent"
member like this:
"notificationContent": { "message": "You clicked $1.", "description": "Tells the user which link they clicked." }
This may seem quicker and less complex, but the other way (using "placeholders"
) is seen as best practice. This is because having the placeholder name (e.g. "url"
) and example helps you to remember what the placeholder is for — a week after you write your code, you'll probably forget what $1
–$8
refer to, but you'll be more likely to know what your placeholder names refer to.
It is also possible to include hardcoded strings in placeholders, so that the same value is used every time, instead of getting the value from a variable in your code. For example:
"mdn_banner": { "message": "For more information on web technologies, go to $MDN$.", "description": "Tell the user about MDN", "placeholders": { "mdn": { "content": "https://developer.mozilla.org/" } } }
In this case we are just hardcoding the placeholder content, rather than getting it from a variable value like $1
. This can sometimes be useful when your message file is very complex, and you want to split up different values to make the strings more readable in the file, plus then these values could be accessed programmatically.
In addition, you can use such substitutions to specify parts of the string that you don't want to be translated, such as person or business names.
Locales can be specified using only a language code, like fr
or en
, or they may be further qualified with a region code, like en_US
or en_GB
, which describes a regional variant of the same basic language. When you ask the i18n system for a string, it will select a string using the following algorithm:
messages.json
file for the exact current locale, and it contains the string, return it.en_US
) and there is a messages.json
file for the regionless version of that locale (e.g. en
), and that file contains the string, return it.messages.json
file for the default_locale
defined in the manifest.json
, and it contains the string, return it.Take the following example:
{ "colorLocalised": { "message": "colour", "description": "Color." }, ... }
{ "colorLocalised": { "message": "color", "description": "Color." }, ... }
{ "colorLocalised": { "message": "couleur", "description": "Color." }, ...}
Suppose the default_locale
is set to fr
, and the browser's current locale is en_GB
:
getMessage("colorLocalised")
, it will return "colour".en_GB
, then getMessage("colorLocalised")
, would return "color", not "couleur".The i18n module provides us with some predefined messages, which we can call in the same way as we saw earlier in Calling message strings from manifests and extension CSS. For example:
__MSG_extensionName__
Predefined messages use exactly the same syntax, except with @@
before the message name, for example
__MSG_@@ui_locale__
The following table shows the different available predefined messages:
Message name | Description |
---|---|
@@extension_id | The extension's internally-generated UUID. You might use this string to construct URLs for resources inside the extension. Even unlocalized extensions can use this message. You can't use this message in a manifest file. Also note that this ID is not the add-on ID returned by |
@@ui_locale | The current locale; you might use this string to construct locale-specific URLs. |
@@bidi_dir | The text direction for the current locale, either "ltr" for left-to-right languages such as English or "rtl" for right-to-left languages such as Arabic. |
@@bidi_reversed_dir | If the @@bidi_dir is "ltr", then this is "rtl"; otherwise, it's "ltr". |
@@bidi_start_edge | If the @@bidi_dir is "ltr", then this is "left"; otherwise, it's "right". |
@@bidi_end_edge | If the @@bidi_dir is "ltr", then this is "right"; otherwise, it's "left". |
Going back to our earlier example, it would make more sense to write it like this:
header { background-image: url(../images/__MSG_@@ui_locale__/header.png); }
Now we can just store our local specific images in directories that match the different locales we are supporting — en, de, etc. — which makes a lot more sense.
Let's look at an example of using @@bidi_*
messages in a CSS file:
body { direction: __MSG_@@bidi_dir__; } div#header { margin-bottom: 1.05em; overflow: hidden; padding-bottom: 1.5em; padding-__MSG_@@bidi_start_edge__: 0; padding-__MSG_@@bidi_end_edge__: 1.5em; position: relative; }
For left-to-right languages such as English, the CSS declarations involving the predefined messages above would translate to the following final code lines:
direction: ltr; padding-left: 0; padding-right: 1.5em;
For a right-to-left language like Arabic, you'd get:
direction: rtl; padding-right: 0; padding-left: 1.5em;
Starting in Firefox 45, you can install extensions temporarily from disk. Do this, and then try testing out our notify-link-clicks-i18n extension. Go to one of your favorite websites and click a link to see if a notification appears reporting the URL of the clicked link.
Next, change Firefox's locale to one supported in the extension that you want to test.
intl.locale.requested
preference (bear in mind that before Firefox 59, this pref is called general.useragent.locale
).""
), which will cause the browser to use the OS default locale.intl.locale.requested
preference does not exist, right-click the list of preferences (or activate the context menu using the keyboard), and choose "New" followed by "String". Enter intl.locale.requested
for the preference name and, "de", or "nl", etc. for the preference value, as described in step 2 above.intl.locale.matchOS
and, if the preference exists and has the value true
, double-click it so that it is set to false
.Note: This works to change the browser's locale, even if you haven't got the language pack installed for that language. You'll just get the browser UI in your default language if this is the case.
Note: To change the result of getUILanguage
the language pack is required, since it reflects the browser UI language and not the language used for extension messages.
Load the extension temporarily from disk again, then test your new locale:
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Internationalization