Skip to content

Instantly share code, notes, and snippets.

@Infocatcher
Last active December 19, 2015 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Infocatcher/5891622 to your computer and use it in GitHub Desktop.
Save Infocatcher/5891622 to your computer and use it in GitHub Desktop.
// https://gist.github.com/Infocatcher/5891622
var menu = [
{ label: "Alert!", cb_id: "alert" },
{ label: "Google", cb_id: "google", image: "https://www.google.com/favicon.ico" },
"menuseparator",
[
"Menu label",
{ label: "Sub item 1", cb_id: "sub" },
{ label: "Sub item 2", cb_id: "sub2" }
],
[
"Menu label 2",
"https://www.google.com/favicon.ico",
{ label: "Sub item 3", cb_id: "sub3" },
{ label: "Sub item 4", cb_id: "sub4" }
]
];
function parseItem(arr, parent) {
if(!parent)
parent = document.createElement("menupopup");
arr.forEach(function(item) {
var node;
if(item == "menuseparator")
node = document.createElement("menuseparator");
else if(Array.isArray(item)) {
node = document.createElement("menu");
node.setAttribute("label", item[0]);
var icon = item[1];
if(typeof icon == "string") {
node.className = "menu-iconic";
node.setAttribute("image", icon);
}
var mp = document.createElement("menupopup");
parseItem(item, mp);
node.appendChild(mp);
}
else if(typeof item == "object" && item) {
node = document.createElement("menuitem");
if(item.hasOwnProperty("image") && !item.hasOwnProperty("class"))
item.class = "menuitem-iconic";
for(var attr in item) if(item.hasOwnProperty(attr))
node.setAttribute(attr, item[attr]);
}
node && parent.appendChild(node);
});
return parent;
}
var mp = parseItem(menu);
mp.setAttribute("oncommand", "this.parentNode.handleCommand(event);");
mp.setAttribute("onclick", "if(event.button != 0) this.parentNode.handleCommand(event);");
mp.setAttribute("oncontextmenu", "return false;");
this.type = "menu";
this.orient = "horizontal";
this.appendChild(mp);
this.handleCommand = function(e) {
var trg = e.target;
var cmd = trg.getAttribute("cb_id");
if(!cmd)
return;
var btn = e.type == "click" && e.button || 0;
btn && closeMenus(trg); // See chrome://browser/content/utilityOverlay.js
alert("Button: " + btn + "\nCommand: " + cmd);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment