右クリックメニューでn階層上がる

現ページの1階層上のページを開くスクリプトは数多くあるけれど、ロケーションバーの右クリックメニューで任意の上位URLに飛べるものは見あたらなかったので作りました。

// ==UserScript==
// -*- mode:JScript; Encoding:utf8n -*-
// @name           upper URI
// @namespace      http://d.hatena.ne.jp/p-arai/
// @description    Add upper URIs to the context menu in Location bar.
//
// @author         p-arai
// @version        2007.08.05


(function()
{
  var attr_name = "item-type";
  var attr_value = "upper-uri-menuitem";
  
  // ポップアップ消去時に URIs とセパレータを削除
  document.getElementById("urlbar").addEventListener("popuphidden", function(event)
  {
    var menupopup = event.originalTarget;
    var items = menupopup.getElementsByAttribute(attr_name, attr_value);
    while(items.length){
      menupopup.removeChild(items[0]);
    }
  }, false);

  // ポップアップ表示時に URIs を調査、メニュー項目を生成
  document.getElementById("urlbar").addEventListener("popupshowing", function(event)
  {
    var menupopup = event.originalTarget;
    var items = menupopup.getElementsByAttribute(attr_name, attr_value);
    var uri_array = getUpURIs();
    if (items.length == 0 && uri_array.length > 0){
      var goUp = function(event)
      {
        if (event.type == "click" && event.button != 1) return;
        loadURI(event.originalTarget.getAttribute("label"));
        menupopup.hidePopup();
      };
      // セパレータ
      var sep = document.createElement("menuseparator");
      sep.setAttribute(attr_name, attr_value);
      menupopup.insertBefore(sep, menupopup.firstChild);
      // URIs
      for(var i=0; i < uri_array.length; i++){
        var menuitem = document.createElement("menuitem");
        menuitem.id = attr_value + i;
        menuitem.setAttribute("label", uri_array[i]);
        menuitem.setAttribute(attr_name, attr_value);
        menuitem.addEventListener("command", goUp, false);
        menuitem.addEventListener("click",   goUp, false);
        menupopup.insertBefore(menuitem, sep);
      }
    }
  }, false);

  var getUpURIs = function()
  {
    var uri_array = [];
    var uri = gBrowser.currentURI;
    var uri_path = uri.path;
    if (uri_path == "/") return [];
    uri_path = uri_path.replace(/\/$/, "");
    var path_array = uri_path.split("/");
    path_array.pop();
    while(path_array.length){
      uri_array.push( uri.prePath + path_array.join("/") + "/" );
      path_array.pop();
    }
    return uri_array;
  };

})();