chrome.i18n

Description

Use thechrome.i18n infrastructure to implement internationalization across your whole app or extension.

Manifest

If an extension has a/_locales directory, themanifest must define"default_locale".

Concepts and usage

You need to put all of its user-visible strings into a file namedmessages.json. Each timeyou add a new locale, you add a messages file under a directory named/_locales/_localeCode_, wherelocaleCode is a code such asen for English.

Here's the file hierarchy for an internationalized extension that supports English (en), Spanish(es), and Korean (ko):

In the extension directory: manifest.json, *.html, *.js, /_locales directory. In the /_locales directory: en, es, and ko directories, each with a messages.json file.

Support multiple languages

Say you have an extension with the files shown in the following figure:

A manifest.json file and a file with JavaScript. The .json file has 'Hello World'. The JavaScript file has title = 'Hello World'.

To internationalize this extension, you name each user-visible string and put it into a messagesfile. The extension's manifest, CSS files, and JavaScript code use each string's name to get itslocalized version.

Here's what the extension looks like when it's internationalized (note that it still has onlyEnglish strings):

In the manifest.json file, 'Hello World' has been changed to '__MSG_extName__', and a new default_locale' item has the value 'en'. In the JavaScript file, 'Hello World' has been changed to chrome.i18n.getMessage('extName'). A new file named /_locales/en/messages.json defines 'extName'.

Some notes about internationalizing:

  • You can use any of thesupported locales. If you use an unsupported locale, Google Chromeignores it.
  • Inmanifest.json and CSS files, refer to a string namedmessagename like this:

    __MSG_messagename__
  • In your extension or app's JavaScript code, refer to a string namedmessagename like this:

    chrome.i18n.getMessage("messagename")
  • In each call togetMessage(), you can supply up to 9 strings to be included in the message. SeeExamples: getMessage for details.

  • Some messages, such as@@bidi_dir and@@ui_locale, are provided by the internationalizationsystem. See thePredefined messages section for a full list of predefined message names.

  • Inmessages.json, each user-visible string has a name, a "message" item, and an optional"description" item. The name is a key such as "extName" or "search_string" that identifies thestring. The "message" specifies the value of the string in this locale. The optional "description"provides help to translators, who might not be able to see how the string is used in yourextension. For example:

    {"search_string":{"message":"hello%20world","description":"The string we search for. Put %20 between words that go together."},...}

For more information, seeFormats: Locale-Specific Messages.

Once an extension is internationalized, translating it is straightforward. You copymessages.json,translate it, and put the copy into a new directory under/_locales. For example, to supportSpanish, just put a translated copy ofmessages.json under/_locales/es. The following figureshows the previous extension with a new Spanish translation.

This looks the same as the previous figure, but with a new file at /_locales/es/messages.json that contains a Spanish translation of the messages.

Predefined messages

The internationalization system provides a few predefined messages to help you localize. Theseinclude@@ui_locale, so you can detect the current UI locale, and a few@@bidi_... messages thatlet you detect the text direction. The latter messages have similar names to constants in thegadgets BIDI (bi-directional) API.

The special message@@extension_id can be used in the CSS and JavaScript files, whether or not theextension or app is localized. This message doesn't work in manifest files.

The following table describes each predefined message.

Message nameDescription
@@extension_idThe extension or app ID; you might use this string to construct URLs for resources inside the extension. Even unlocalized extensions can use this message.
Note: You can't use this message in a manifest file.
@@ui_localeThe current locale; you might use this string to construct locale-specific URLs.
@@bidi_dirThe 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_dirIf the@@bidi_dir is "ltr", then this is "rtl"; otherwise, it's "ltr".
@@bidi_start_edgeIf the@@bidi_dir is "ltr", then this is "left"; otherwise, it's "right".
@@bidi_end_edgeIf the@@bidi_dir is "ltr", then this is "right"; otherwise, it's "left".

Here's an example of using@@extension_id in a CSS file to construct a URL:

body{background-image:url('chrome-extension://__MSG_@@extension_id__/background.png');}

If the extension ID is abcdefghijklmnopqrstuvwxyzabcdef, then the bold line in the previous codesnippet becomes:

background-image:url('chrome-extension://abcdefghijklmnopqrstuvwxyzabcdef/background.png');

Here's 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 bold lines become:

dir:ltr;padding-left:0;padding-right:1.5em;

Locales

You can choose from many locales, including some (such asen) that let a single translation support multiple variations of a language (such asen_GB anden_US).

You can localize your extension to any locale that is supported by the Chrome Web Store. If your locale is not listed here, choose the closest alternative. For example, if the default locale of your extension is"de_CH", choose"de" in the Chrome Web Store.

Locale codeLanguage (region)
arArabic
amAmharic
bgBulgarian
bnBengali
caCatalan
csCzech
daDanish
deGerman
elGreek
enEnglish
en_AUEnglish (Australia)
en_GBEnglish (Great Britain)
en_USEnglish (USA)
esSpanish
es_419Spanish (Latin America and Caribbean)
etEstonian
faPersian
fiFinnish
filFilipino
frFrench
guGujarati
heHebrew
hiHindi
hrCroatian
huHungarian
idIndonesian
itItalian
jaJapanese
knKannada
koKorean
ltLithuanian
lvLatvian
mlMalayalam
mrMarathi
msMalay
nlDutch
noNorwegian
plPolish
pt_BRPortuguese (Brazil)
pt_PTPortuguese (Portugal)
roRomanian
ruRussian
skSlovak
slSlovenian
srSerbian
svSwedish
swSwahili
taTamil
teTelugu
thThai
trTurkish
ukUkrainian
viVietnamese
zh_CNChinese (China)
zh_TWChinese (Taiwan)

Search for messages

You don't have to define every string for every supported locale. As long as the default locale'smessages.json file has a value for every string, your extension or app will run no matter howsparse a translation is. Here's how the extension system searches for a message:

  1. Search the messages file (if any) for the user's preferred locale. For example, when GoogleChrome's locale is set to British English (en_GB), the system first looks for the message in/_locales/en_GB/messages.json. If that file exists and the message is there, the system looksno further.
  2. If the user's preferred locale has a region (that is, the locale has an underscore: _), searchthe locale without that region. For example, if theen_GB messages file doesn't exist ordoesn't contain the message, the system looks in theen messages file. If that file exists andthe message is there, the system looks no further.
  3. Search the messages file for the default locale. For example, if the extension's"default_locale" is set to "es", and neither/_locales/en_GB/messages.json nor/_locales/en/messages.json contains the message, the extension uses the message from/_locales/es/messages.json.

In the following figure, the message named "colores" is in all three locales that the extensionsupports, but "extName" is in only two of the locales. Wherever a user running Google Chrome in USEnglish sees the label "Colors", a user of British English sees "Colours". Both US English andBritish English users see the extension name "Hello World". Because the default language is Spanish,users running Google Chrome in any non-English language see the label "Colores" and the extensionname "Hola mundo".

Four files: manifest.json and three messages.json files (for es, en, and en_GB). The es and en files show entries for messages named 'extName' and 'colores'; the en_GB file has just one entry (for 'colores').

Set your browser's locale

To test translations, you might want to set your browser's locale. This section tells you how to setthe locale inWindows,Mac OS,Linux, andChromeOS.

Windows

You can change the locale using either a locale-specific shortcut or the Google Chrome UI. Theshortcut approach is quicker, once you've set it up, and it lets you use several languages at once.

Use a locale-specific shortcut

To create and use a shortcut that launches Google Chrome with a particular locale:

  1. Make a copy of the Google Chrome shortcut that's already on your desktop.
  2. Rename the new shortcut to match the new locale.
  3. Change the shortcut's properties so that the Target field specifies the--lang and--user-data-dir flags. The target should look something like this:

    path_to_chrome.exe --lang=locale --user-data-dir=c:\locale_profile_dir
  4. Launch Google Chrome by double-clicking the shortcut.

For example, to create a shortcut that launches Google Chrome in Spanish (es), you might create ashortcut namedchrome-es that has the following target:

path_to_chrome.exe --lang=es --user-data-dir=c:\chrome-profile-es

You can create as many shortcuts as you like, making it straightforward to test in multiple languages. Forexample:

path_to_chrome.exe --lang=en --user-data-dir=c:\chrome-profile-enpath_to_chrome.exe --lang=en_GB --user-data-dir=c:\chrome-profile-en_GBpath_to_chrome.exe --lang=ko --user-data-dir=c:\chrome-profile-ko
Note: Specifying--user-data-dir is optional but handy. Having one data directory per localelets you run the browser in several languages at the same time. A disadvantage is that because thelocales' data isn't shared, you have to install your extension multiple times—once per locale,which can be challenging when you don't speak the language. For more information, seeCreating and Using Profiles.
Use the UI

Here's how to change the locale using the UI on Google Chrome for Windows:

  1. App icon >Options
  2. Choose theUnder the Hood tab
  3. Scroll toWeb Content
  4. ClickChange font and language settings
  5. Choose theLanguages tab
  6. Use the drop down to set theGoogle Chrome language
  7. Restart Chrome

Mac OS

To change the locale on Mac, you use the system preferences.

  1. From the Apple menu, chooseSystem Preferences
  2. Under thePersonal section, chooseInternational
  3. Choose your language and location
  4. Restart Chrome

Linux

To change the locale on Linux, first quit Google Chrome. Then, all in one line, set the LANGUAGEenvironment variable and launch Google Chrome. For example:

LANGUAGE=es ./chrome

ChromeOS

To change the locale on ChromeOS:

  1. From the system tray, chooseSettings.
  2. Under theLanguages and input section, choose theLanguage drop-down.
  3. If your language is not listed, clickAdd languages and add it.
  4. Once added, click the 3-dotMore actions menu item next to your language and chooseDisplay ChromeOS in this language.
  5. Click theRestart button that appears next to the set language to restart ChromeOS.

Examples

You can find examples of internationalization in theexamples/api/i18n directory. For acomplete example, seeexamples/extensions/news. For other examples and for help in viewing thesource code, seeSamples.

getMessage()

The following code gets a localized message from the browser and displays it as a string. Itreplaces two placeholders within the message with the strings "string1" and "string2".

functiongetMessage(){varmessage=chrome.i18n.getMessage("click_here",["string1","string2"]);document.getElementById("languageSpan").innerHTML=message;}

Here's how you'd supply and use a single string:

// In JavaScript codestatus.innerText=chrome.i18n.getMessage("error",errorDetails);
"error":{"message":"Error: $details$","description":"Generic error template. Expects error parameter to be passed in.","placeholders":{"details":{"content":"$1","example":"Failed to fetch RSS feed."}}}

For more information about placeholders, see theLocale-Specific Messages page. For details oncallinggetMessage(), see theAPI reference.

getAcceptLanguages()

The following code gets accept-languages from the browser and displays them as a string byseparating each accept-language with ','.

functiongetAcceptLanguages(){chrome.i18n.getAcceptLanguages(function(languageList){varlanguages=languageList.join(",");document.getElementById("languageSpan").innerHTML=languages;})}

For details on callinggetAcceptLanguages(), see theAPI reference.

detectLanguage()

The following code detects up to 3 languages from the given string and displays the result asstrings separated by new lines.

functiondetectLanguage(inputText){chrome.i18n.detectLanguage(inputText,function(result){varoutputLang="Detected Language: ";varoutputPercent="Language Percentage: ";for(i=0;i <result.languages.length;i++){outputLang+=result.languages[i].language+" ";outputPercent+=result.languages[i].percentage+" ";}document.getElementById("languageSpan").innerHTML=outputLang+"\n"+outputPercent+"\nReliable: "+result.isReliable;});}

For more details on callingdetectLanguage(inputText), see theAPI reference.

Types

LanguageCode

Chrome 47+

An ISO language code such asen orfr. For a complete list of languages supported by this method, seekLanguageInfoTable. For an unknown language,und will be returned, which means that [percentage] of the text is unknown to CLD

Type

string

Methods

detectLanguage()

PromiseChrome 47+
chrome.i18n.detectLanguage(
  text: string,
  callback?: function,
)

Detects the language of the provided text using CLD.

Parameters

  • text

    string

    User input string to be translated.

  • callback

    function optional

    Thecallback parameter looks like:

    (result: object) => void

    • result

      object

      LanguageDetectionResult object that holds detected langugae reliability and array of DetectedLanguage

      • isReliable

        boolean

        CLD detected language reliability

      • languages

        object[]

        array of detectedLanguage

        • language

          string

        • percentage

          number

          The percentage of the detected language

Returns

  • Promise<object>

    Chrome 99+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

getAcceptLanguages()

Promise
chrome.i18n.getAcceptLanguages(
  callback?: function,
)

Gets the accept-languages of the browser. This is different from the locale used by the browser; to get the locale, usei18n.getUILanguage.

Parameters

  • callback

    function optional

    Thecallback parameter looks like:

    (languages: string[]) => void

    • languages

      string[]

      Array of LanguageCode

Returns

  • Promise<LanguageCode[]>

    Chrome 99+

    Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. You cannot use both on the same function call. The promise resolves with the same type that is passed to the callback.

getMessage()

chrome.i18n.getMessage(
  messageName: string,
  substitutions?: any,
  options?: object,
)

Gets the localized string for the specified message. If the message is missing, this method returns an empty string (''). If the format of thegetMessage() call is wrong — for example,messageName is not a string or thesubstitutions array has more than 9 elements — this method returnsundefined.

Parameters

  • messageName

    string

    The name of the message, as specified in themessages.json file.

  • substitutions

    any optional

    Up to 9 substitution strings, if the message requires any.

  • options

    object optional

    Chrome 79+
    • escapeLt

      boolean optional

      Escape< in translation to&lt;. This applies only to the message itself, not to the placeholders. Developers might want to use this if the translation is used in an HTML context. Closure Templates used with Closure Compiler generate this automatically.

Returns

  • string

    Message localized for current locale.

getUILanguage()

chrome.i18n.getUILanguage()

Gets the browser UI language of the browser. This is different fromi18n.getAcceptLanguages which returns the preferred user languages.

Returns

  • string

    The browser UI language code such as en-US or fr-FR.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-02-12 UTC.