Adding i18n languages to your Chrome extension

A majority of the users on my temp mail Chrome extension consume the English language, however a sizeable percentage of them do not - so why not try support them?

The overall implementation is fairly straightforward and didn’t require too much fiddling around. By far the most tedious part is extracting the existing text and putting it into the appropriate json config. From there, the extension does the rest really.

Changing your Manifest

You’ll need to make a few adjustments to your manifest to let Chrome know what the default language is, and how to name the app in different locales. The main changes are as follows:

{
  "name": "__MSG_namechrome__",
  "description": "__MSG_description__",
  "default_locale": "en"
}

Folder and file structure

You’ll need to add a few new folders and files for each locale you wish to support. For that, your folder structure should be as such: /_locales/<lang>/messages.json

So if you wanted to support English, English UK, English US and French your folder structure would look like this:

/_locale
  /en/messages.json
  /en_uk/messages.json
  /en_us/messages.json
  /fr/messages.json

Naturally each file contains the relevant json containing the same keys but with language specific values. To give you an example, here’s the first few lines from my extension:

{
  "name": {"message": "My App"},
  "namechrome": {"message": "My App name on Chrome Store"},
  "description": {"message": "My app description in the Chrome Store"},

  "welcomeHeader": {"message": "Welcome to my new app!"},
  ...

Loading the content into the app

With your content copied out into the json file, you’ll now want to start replacing it with an i18n attribute. Changing <p>Welcome to my app</p> tags for something like <p i18n="welcomeHeader"></p>.

Using the following code, we can then scan for the tag, and place the values as innerHTML values, allowing Chrome to detect the locale and load in the appropriate text.

var i18nElements = document.querySelectorAll("[i18n]");
i18nElements.forEach(function(element) {
    var i18nKey = element.getAttribute("i18n");
    element.innerHTML = chrome.i18n.getMessage(i18nKey);
});

And that’s pretty much it. You’ll need to call the above for each new screen that’s loaded, but other than that, you’re now ready to start serving different parts of the world in their native language.