Thursday, 20 June 2024
How to localize strings included in a .js file Print
Written by Goofy   
Thursday, 29 September 2005

How to localize strings included in a .js file     

The problem is : sometimes, extensions have locale folders with localized strings, but some little bits of words and sentences remain, which you cannot transform in entities as usual, because they belong to a .js file.
Suppose you have found these strings nested in a .js file:

if ( password == userPassword ) {
      oPrefs.setBoolPref("access.authenticated", true);  
   else {
      alert ("Invalid password");
function clear()
 sure = confirm("Are you sure?");
First, you have to find or create a file in your locale folder. Then you  simply write  variable names and the sentences or words that should appear to the final user.

Something like :

WrongPassMessage=Invalid  password
AreYouSureMessage=Are you sure?

(where Invalid password and Are you sure?  are the strings to be displayed to the final user)
Notice : a simple = sign is enough

Now you go back to the .js file where the strings to be localized are nested.
At the very beginning of the file you create one string bundle with the address of the properties file where to find strings.

var gBundle = Components.classes[";1"].getService(Components.interfaces.nsIStringBundleService);
var mystrings = gBundle.createBundle("chrome://myextension/locale/");

Then you list immediately below every variable you need for the .js file you are managing :

var wrongpassalert = mystrings.GetStringFromName("WrongPassMessage");
var confirmmessage=mystrings.GetStringFromName("AreYouSureMessage");
You can now use your variables in the .js where they  are needed: see examples below

if ( password == userPassword ) {
      oPrefs.setBoolPref("access.authenticated", true);   
   else {
      alert (wrongpassalert);

function clear()
 sure = confirm(confirmmessage);

Last Updated ( Wednesday, 27 June 2007 )
Top! Top!
'; ?>