Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

このページは、小さく、見ればすぐわかるようなコード片を載せています。

ウェブページをローカルファイルに保存する

次のコードはユーザにファイル名を入力するように聞いてきませんが、それは ファイルピッカーコンポーネント を使用することで可能です。

var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);

file.initWithPath("C:\\filename.html");

var wbp = Components.classes['@mozilla.org/embedding/browser/nsWebBrowserPersist;1']
  .createInstance(Components.interfaces.nsIWebBrowserPersist);
wbp.saveDocument(content.document, file, null, null, null, null);

Downloading Files も見てください。

任意のURLをローカルファイルに保存する

var file = Components.classes["@mozilla.org/file/local;1"]
                     .createInstance(Components.interfaces.nsILocalFile);

file.initWithPath("C:\\filename.html");

var wbp = Components.classes['@mozilla.org/embedding/browser/nsWebBrowserPersist;1']
                    .createInstance(Components.interfaces.nsIWebBrowserPersist);
var ios = Components.classes['@mozilla.org/network/io-service;1']
                    .getService(Components.interfaces.nsIIOService);
var uri = ios.newURI("https://www.google.com/", null, null);

wbp.saveURI(uri, null, null, null, null, file);

Downloading Files も見てください。

オペレーティングシステムを検出する

// Windows Vista, XP, 2000, NT では "WINNT" が返る。
// GNU/Linux では "Linux" 。Mac OS X では "Darwin" が返る。
var osString = Components.classes["@mozilla.org/xre/app-info;1"]
                         .getService(Components.interfaces.nsIXULRuntime).OS;

nsIXULRuntime が手に入らないケース (古い SeaMonkey のバージョン) では、 nsIHttpProtocolHandler.oscpunavigator.oscpu を使うことができます:

Components.classes["@mozilla.org/network/protocol;1?name=http"]
          .getService(Components.interfaces.nsIHttpProtocolHandler).oscpu;

ホストアプリケーションとそのバージョンを検出する

var info = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULAppInfo);
// このコードを実行しているアプリケーションの名前を取得する
info.name; // Firefox では "Firefox" が返る
info.version; // Firefox バージョン 2.0.0.1 では "2.0.0.1" が返る

拡張機能の install.rdf に記載されたその拡張機能のバージョンを読み出す

var em = Components.classes["@mozilla.org/extensions/manager;1"]
                   .getService(Components.interfaces.nsIExtensionManager);

// [email protected] をバージョンを読み出したい拡張機能の GUID に変更すること
// 例えば FoxyProxy なら [email protected]
var addon = em.getItemForID("[email protected]");
var version = addon.version;

入力ストリームから出力ストリームにコピーする

// istream は nsIInputStream、ostream は nsIOutputStream

// 出力ストリームを機能させるにはバッファリングする必要がある
var bostream = Components.classes["@mozilla.org/network/buffered-output-stream;1"]
                    .createInstance(Components.interfaces.nsIBufferedOutputStream);
bostream.init(ostream, 0x8000);

// 入力ストリームから読み込むためにストリームポンプとストリームリスナを用意する
var pump = Components.classes["@mozilla.org/network/input-stream-pump;1"]
                     .createInstance(Components.interfaces.nsIInputStreamPump);
pump.init(istream, -1, -1, 0, 0, true);

/* ファイルを閉じるべきタイミングを知るために独自のオブザーバが必要 */
var observer = {
  onStartRequest: function(aRequest, aContext) {},
  onStopRequest: function(aRequest, aContext, aStatusCode) {
    bostream.close();
  }
};

// 出力ストリームに書き出すためにシンプルストリームリスナを用意する
var listener = Components.classes["@mozilla.org/network/simple-stream-listener;1"]
                         .createInstance(Components.interfaces.nsISimpleStreamListener);
listener.init(bostream, observer);

// コピー開始
pump.asyncRead(listener, null);

Firefox/Thunderbird を再起動する

アプリケーションを再起動する単純な方法を提供することで、 バグ 338039は改善しています。

マウス、キーイベントをシミュレートする

nsIDOMWindowUtils インタフェースにはマウスイベントやキーイベントをシミュレートするための有用なメソッドがあります。

Firefox 3 / Gecko 1.9 の新機能

var req = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
var utils = req.getInterface(Components.interfaces.nsIDOMWindowUtils);

utils.sendMouseEvent("mousedown", 10, 10, 0, 1, 0);
utils.sendMouseEvent("mouseup", 10, 10, 0, 1, 0);

貧弱な難読化

このコードは幾分敏感なデータ(例えば拡張機能のパスワード)をぱっと見では発見できないようにするための小細工です。一見ちんぷんかんぷんですが、これは簡単に破られてしまいます。パスワードの保存については、 このドキュメントnsIPasswordManager の使用について説明しています。

function encrypt(val) {
	num_out = "";
	if(val == "") {
		return "";
	}else {
		str_in = escape(val);
		for(i = 0; i < str_in.length; i++) {
			num_out += str_in.charCodeAt(i) - 23;
		}
		return unescape(num_out);
	}
}

function decrypt(val) {
	str_out = "";
	if(val == "") {
		return "";
	} else {
		num_out = val;  
		for(i = 0; i < num_out.length; i += 2) {
			num_in = parseInt(num_out.substr(i,[2])) + 23;
			num_in = unescape('%' + num_in.toString(16));
			str_out += num_in;
		}
		return str_out;
	}
}

マウスホイールイベントの検出

エレメント上でマウスホイールを回転させたとき、 DOMMouseScroll イベントが起こります。 event.detail はスクロールした行の数を含みます。このイベントは Mozilla オンリーです。他のブラウザでは window.onmousewheel をサポートしているかもしれません。

<div id="scrollArea" style="overflow: scroll; height: 6em; width: 10em;">
	This is the scrolling area.
	This is the scrolling area.
	This is the scrolling area.
	This is the scrolling area.
	This is the scrolling area.
	This is the scrolling area.
	This is the scrolling area.
	This is the scrolling area.
	This is the scrolling area.
	This is the scrolling area.
	This is the scrolling area.
	This is the scrolling area.
</div>

<script type="text/javascript">
	var elm = document.getElementById("scrollArea");
	elm.addEventListener("DOMMouseScroll", function scroll(event){
		//event.detail は下へスクロールしたとき正、上へスクロールしたとき負です。
		alert("scrolling " + event.detail + " lines");
	}, false);
</script>

もし何か修飾キー(Ctrl,Shift,Alt,Meta)を押しているときは DOMMouseScroll イベントを受け取れないなら、 mousewheel.withcontrolkey.action と関連するプリファレンスをチェックするべきです。 action のプリファレンスの意味は下のテーブルに書かれています。

mousewheel.withXXXkey.action Result
0 行ごとにスクロール。これにセットされているとき、 DOMMouseScroll イベントを受け取る。
1 ページごとにスクロール。
2 履歴の中を動く。これにセットされているとき、 DOMMouseScroll イベントを受け取らない。
3 テキストサイズを変更する。これにセットされているとき、 DOMMouseScroll イベントを受け取らない。

ふつうのクリックイベントと同じように、マウスホイールクリックイベントをリスンすることができます。マウスホイールがクリックされたとき、 event.button は 2 と等しくなります。

カーソルの位置にテキストを挿入する

function insertText(element, snippet) {
  var selectionEnd = element.selectionStart + snippet.length;
  var currentValue = element.value;

  var beforeText = currentValue.substring(0, element.selectionStart);
  var afterText = currentValue.substring(element.selectionEnd, currentValue.length);

  element.value = beforeText + snippet + afterText;
  element.focus();

  //挿入したテキストの後にカーソルを置く
  element.setSelectionRange(selectionEnd, selectionEnd);
}

insertText(window.content.document.getElementById("example"), "the text to be inserted");

上記コードは、フォーム内の<input type="text" id="example">内に記載されたテキストに文字を追記するコードです。

何も無い<div id="example">テキスト</div>等に追加されるわけではありません。

現在選択されているテキストを取得

browser.xul にオーバーレイしている状況で、

var selectedText = document.commandDispatcher.focusedWindow.getSelection().toString();

も見てください。

プログラムから JavaScript を無効化する

// browser.xul から現在のアクティブなタブでJSを無効化する
getBrowser().docShell.allowJavascript = false;

もしこれがあなたのブラウザでないなら、値を保存し、終了したとき復元するべきです。もしそのURI上の選択されているスクリプトをブロックしたいなら、 nsIContentPolicy を実行します。

ロードされたドキュメントでどの要素がフォーカスを持っているのか見つける

// focussedControl はフォーカスされている領域を記憶し、何もないときは null になります。
// 単純のためテキストエリアは除外していますが、 onPageLoad() はテキストエリアも同様に調べるように 
// 簡単に修正できます。さらなる強化では、動的にページに加えられた(例えばページのjavascriptによって)
// フィールドの取り扱いを含めることができます。

var focussedControl;

window.addEventListener("load", function(e) { onWindowLoad(e); }, false);

function onWindowLoad() {
  addEventListener("load", onPageLoad, true);
}

function onPageLoad() {
  var pageDoc = document.commandDispatcher.focusedWindow.document;
  var inputList = pageDoc.getElementsByTagName('input');

  for (var i = 1; i < inputList.length; i++) {
    inputList.item(i).
      addEventListener("focus", function(e) {onFocusInput(e);}, false);
    inputList.item(i).
      addEventListener("blur", function(e) {onBlurInput(e);}, false);
  }
}

function onFocusInput(focusEvent) {
  focussedControl = focusEvent.originalTarget;
}

function onBlurInput(blurEvent) {
  focussedControl = null;
}

拡張機能が無効化/アンインストールされる前に通知を受け取る

xulplanet entry on global notifications

  • notification: "em-action-requested"
  • aData: "item-disabled"
  • aSubject は nsIUpdateItem インスタンス。

この通知は拡張機能が無効化されるとき、ただし実際に無効化される前に伝わります。ユーザは再起動の前にその動作を取りやめることができます。その場合、拡張機能は無効化されません。この通知を受け取ったとき、フラグをセットし(そしてユーザが動作をキャンセルしたときは外し)、終了の時に掃除することができます。欠点はFirefoxが不適切に終了したときコードが実行されないということです。

アイテムIDを読み取ってあなたの拡張機能に対してだけコードを実行するようにすべきです。

JavaScript から文字列バンドルを使う

拡張機能が次のような設定名/値のペアを持った myext.properties を持っているとします:

 invalid.url=The speficied URL, %S, is invalid. That was attempt number %S.

これらのプロパティは JavaScript から次のようにアクセスできます:

var common = {
 
  _bundle: Components.classes["@mozilla.org/intl/stringbundle;1"]
    .getService(Components.interfaces.nsIStringBundleService)
    .createBundle("chrome://myext/locale/myext.properties"),
 
  getLocalizedMessage: function(msg) {
    return this._bundle.GetStringFromName(msg);
  }
};
 
alert(common.getLocalizedMessage("invalid.url"));

もう一つの似た代替方法 (GetStringFromName と formatStringFromName の両方を使う)は:

var fcBundle = Components.classes["@mozilla.org/intl/stringbundle;1"]
						.getService(Components.interfaces.nsIStringBundleService)
						.createBundle("chrome://myext/locale/myext.properties");

function getStr(msg, args){ //get localised message
	if (args) {
       args = Array.prototype.slice.call(arguments, 1);
       return fcBundle.formatStringFromName(msg,args,args.length);
	} else {
		return fcBundle.GetStringFromName(msg);
	}
}

/* Usage */
alert(getStr("invalid.url", "https://bad/url/", "3")); //パラメータ付きのメッセージ
alert(getStr("invalid.url")); //パラメータ無しのメッセージ

ドキュメントのタグと貢献者

 このページの貢献者: ethertank, kobashi, masahal, Mgjbot, Electrolysis
 最終更新者: ethertank,