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:
- You'll probably use
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.
- The
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.
- The
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:
let title = browser.i18n.getMessage("notificationTitle");
let 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.