Search code examples
firefoxfirefox-addonfirefox-addon-sdk

Firefox string resources: How to get localized friendly languages names?


I'm developing a Firefox extension that involves dictionaries in various languages and dialects. I want to display a dialog to the user to select spell checking dictionaries for the available languages. It will be tedious for the user to select from values like en-US, ar-EG, en-GB, etc., so, I want to display the localized language names like what Firefox does in this screenshot Dictionaries

This is the dictionary selection menu on my Arabic Firefox displaying the names of the two languages en-US and ar.

How to do such thing?


Solution

  • Here is what I did to find and use these strings:

    1- I downloaded the whole Firefox source code and extracted it.

    2- I searched the source files for the name "New Zealand". This unique country name should exist only in the file I'm looking for. Rather than using general terms like English, United States, Arabic, etc.

    3- The search led me to two interesting files: regionNames.properties and languageNames.properties. The first has the names of all countries and the other has the names of all languages. Firefox should be using the two sets of strings to display dictionary names.

    4- I found that the two files can be fetched from the URLs chrome://global/locale/languageNames.properties and chrome://global/locale/regionNames.properties, so, I used the string bundle service and the string bundle objects to load and use the resources.

    Here's a code sample:

    • On the top of my main.js file:

      const {Cc, Ci, Cu}  = require("chrome"),
            stringBundles = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
      
    • Then I have this piece of code in another method:

      let languagesNamesBundle = stringBundles.createBundle("chrome://global/locale/languageNames.properties"),
          countriesNames = stringBundles.createBundle("chrome://global/locale/regionNames.properties");
      
      console.log(languagesNamesBundle.GetStringFromName("ar")); // العربية Arabic
      console.log(languagesNamesBundle.GetStringFromName("af")); // الأفريكانية Afrikaans
      console.log(countriesNames.GetStringFromName("fj")); // فيجي Fiji
      console.log(countriesNames.GetStringFromName("cr")); // كوستا ريكا Costa Rica
      

    And this is what I wanted. Now I can compose dictionary names from languages and countries names. I'll update the answer to add the path of the project repository after I publish the final result.