views:

104

answers:

1

In the 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 curious if there's any reason I shouldn't be doing this, or if there's anything wrong with the code. The following is in my init method that gets 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 = ...?)

+1  A: 

Far as I know there is no built in getTabForBrowser function, so you would have to roll your own. However, your code assumes that browser nodes are stored in the same DOM order as tab nodes. I can't say for sure if this assumption is ever broken, but considering tabs can be re-positioned by the user arbitrarily, it is not something I'd rely on.

Fortunately, each tab object has a linkedBrowser property. So you could rewrite your code like so:

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;
}
MooGoo
Should it be `==` or `===`? I think it's conceivable that two `<browser>`s would compare as equal even though they aren't exactly the same browser, although I'm not sure. So `===` seems safer to me.
MatrixFrog
After some quick experimenting, it looks like it *does* reorder the browsers in the DOM, but you're right that I shouldn't rely on that. Good point!
MatrixFrog
MooGoo