| « 「nsIRDFObserver を使ってブックマークのデータソースの動きを調べる」の使用例 | [userChrome.js] 「最近閉じたタブ」のエントリを中クリックしてタブを開き直す » |
nsIStringBundleService
JavaScript内でローカライズされた文字列(平たく言えば日本語)を使用するには、properties ファイルを xul:stringbundle 要素から参照して getString や getFormattedString によって文字列を取り出す方法がある。これは XUL Tutorial にも記載されているように基本的な方法である。
しかし、ユーザーインターフェースとは切り離されたプログラム的な制御がメインの JavaScript にてローカライズされた文字列を使用する場合(特に自前のXPCOMコンポーネントを実装する場合)、いちいち xul へ stringbundle 要素を配置するのは面倒であり、規模が大きくなるとややこしくなりやすい。こういう場合には nsIStringBundleService が便利である。このXPCOMサービスは createBundle メソッドによって指定したURIから properties ファイルを読み込んで nsIStringBundle 型のXPCOMオブジェクトを生成し、 GetStringFromName や formatStringFromName メソッドによってローカライズされた文字列を取り出したりすることができる。以下のサンプルにある getLocaleString 関数は、 BookmarksUtils を参考にして文字列の置換の有無に両対応したものである。
リファレンス:
Interface Reference – nsIStringBundleService
Interface Reference – nsIStringBundle
sample.properties
HELLO=こんにちは MY_NAME_IS=私の名前は%Sです。
sample.js
var FoxkehUtils = {
_stringBundle : null,
getLocaleString : function(aStringKey, aReplacements)
{
// 初めて呼び出された時に properties ファイルを読み込んで nsIStringBundle オブジェクト生成
if ( !this._stringBundle ) {
const BUNDLE_SVC = Components.classes['@mozilla.org/intl/stringbundle;1'].getService(Components.interfaces.nsIStringBundleService);
this._stringBundle = BUNDLE_SVC.createBundle("chrome://sample/locale/sample.properties");
}
try {
if ( !aReplacements )
// 置換なし
return this._stringBundle.GetStringFromName(aStringKey);
else
// 置換あり
return this._stringBundle.formatStringFromName(aStringKey, aReplacements, aReplacements.length);
} catch(ex) {
// 未定義の場合 fallout
return aStringKey;
}
},
say : function()
{
alert(this.getLocaleString("HELLO")); // こんにちは
alert(this.getLocaleString("MY_NAME_IS", ["フォクすけ"])); // 私の名前はフォクすけです。
},
}
FoxkehUtils.say();