Tuesday, March 27, 2007

Tab/Browser source for an event

Do you want to find out what browser (tab) an event comes from? That is a tricky think to do if you have no idea (and not so easy to find). I found it in MozillaZine forum. In case it is not available or the discussion gets removed, that is the code (for Firefox 2.0):


function exampleLoadListener(event) {
var doc = event.originalTarget;
// make sure to get the top frame
doc = doc.defaultView.top.document;
var browser = gBrowser.getBrowserForDocument(doc);
var tabIndex = gBrowser.browsers.indexOf(browser);

alert(tabIndex + " - " + doc.title);
}
getBrowser().addEventListener("load", exampleLoadListener, true);


If you want to use it with Firefox 1.5, there is no getBrowserForDocument(). You must replace it with getBrowserIndexForDocument(). And, with the browser index, call gBrowser.getBrowserAtIndex() to get the browser object itself. Of course, if you want the tab itself, you can use gBrowser.tabContainer.childNodes[tabIndex].
Post a Comment