Firefox gBrowser.getBrowserForTab but not gBrowser.getTabForBrowser?

In Javascript, for a Firefox extension, you can call gBrowser.getBrowserForTab , but there is no gBrowser.getTabForBrowser . So I wrote my own, and it works, and I'm just wondering if there is any reason why I shouldn't do this, or if something is wrong with the code. The following is the init method, which is called when the window loads.

 gBrowser.getTabForBrowser = function(browser) { for (var i=0; i<gBrowser.browsers.length; i++) { if (gBrowser.getBrowserAtIndex(i) === browser) { return gBrowser.tabContainer.getItemAtIndex(i); } } return null; } 

(or should it be gBrowser.prototype.getTabForBrowser = ... ?)

+4
source share
1 answer

As far as I know, there is no built-in getTabForBrowser function, so you have to minimize it yourself. However, your code assumes that the browser nodes are stored in the same DOM order as the tab nodes. I can’t say for sure if this assumption is ever broken, but given that the tabs can be moved by the user arbitrarily, this is not what I would rely on.

Fortunately, each tab object has a linkedBrowser property. Therefore, you can rewrite your code like this:

 gBrowser.getTabForBrowser = function(browser) { var mTabs = gBrowser.mTabContainer.childNodes; for (var i=0, i<mTabs.length; i++) { if (mTabs[i].linkedBrowser == browser) { return mTabs[i]; } } return null; } 
+3
source

All Articles