0

Who to get the tab Index of the right clicked tab that fires the Tab context-menu. Tab is NOT the active tab (not the selectedIndex)?

As an example. "Close Tabs to the Right" in Tab context menu works regardless of which tab (active/not-active) tab is right-clicked. How does it get the correct tab index?

erosman
  • 7,094
  • 7
  • 27
  • 46

2 Answers2

1

Listen for for the popupshown event of the tabContextMenu element.

Since this a restartless addon I assume that you already have a reference to the ChromeWindow.

var tabContextMenu = chromewin.document.getElementById("tabContextMenu");
tabContextMenu.addEventListener("popupshown", function(){
  var rightclickedtab = chromewin.TabContextMenu.contextTab;
  // now proceed as you wish
}, false);

You can also add your own menu item and listen for its command event.

In any case, remember to cleanup when your extension gets unloaded.

paa
  • 5,048
  • 1
  • 18
  • 22
  • Thank you .... There doesn't seem to be a `contextTab` property in `menupopup id="tabContextMenu"` ... undefined – erosman Oct 06 '14 at 05:51
  • 1
    `TabContextMenu` (note the capital T) is a global variable of the ChromeWindow. – paa Oct 06 '14 at 09:46
  • I missed that ... :) yes.. that is the one .. actually `TabContextMenu.contextTab._tPos` is the one I wanted .. thank you – erosman Oct 06 '14 at 11:59
0

What about on click take the event.target, which is the tab element, then loop through the parentNode of that tab element which has childNoedes of the tabs. then find your event.target in there?

So lick add on click listeners and do this:

var foundAtIndex = -1;
var tab = event.target;
var tabContainer = tab.parentNode;
var tabs = tabContainer.childNodes;
for (var i=0; i<tabs.length; i++) {
if (tabs[i] == tab) {
foundAtIndex = i;
break;
}
}

if (foundAtIndex !== -1) {
console.error('very weird, tab not found');
} else {
console.info('tab found at index:', foundAtIndex);
}
Noitidart
  • 35,443
  • 37
  • 154
  • 323
  • event.target is possible but gets complicated when sub-menus are introduces as the target gets nested. There are other loops involved and for example doing a loop to get the index from an API (`tabContainer.childNodes`) and doing another loop (to get the URL) from another API (`gBrowser.getBrowserAtIndex(i).currentURI`) seems a waste. Unless I can get the `currentURI` from the firm API!? – erosman Oct 06 '14 at 06:51
  • See this topic here: http://forums.mozillazine.org/viewtopic.php?f=19&t=2792651&p=13310951 there is a `.popupNode` attribute so you don't get messed up with sub menus :) let me know if this works out – Noitidart Oct 06 '14 at 21:44
  • Thank you... but [document.popupNode](https://developer.mozilla.org/en-US/docs/Web/API/document.popupNode) – erosman Oct 07 '14 at 04:40
  • Ah yeah deprecated but they have replacement for it: `menupopup property triggerNode` will that work? I think it would be better as its on the menupopup now. – Noitidart Oct 07 '14 at 07:17