Reusing tabs for the same URL

From MozillaZine Knowledge Base

(Difference between revisions)
Revision as of 19:49, 30 March 2005
Grimholtz (Talk | contribs)
(added links per discussion)
<-- Previous diff
Revision as of 11:49, 9 August 2005
Asqueella (Talk | contribs)

Next diff -->
Line 45: Line 45:
</pre> </pre>
-This code uses techniques discussed in [[Enumerating tabbrowser tabs|Enumerating tabbrowser tabs]] and [[Dev : Extensions : Example Code : Opening a new browser window|Opening a new browser window]].+This code uses techniques discussed in [[Enumerating tabbrowser tabs|Enumerating tabbrowser tabs]] and [[Opening a new browser window (development)|Opening a new browser window]].
[[Category:Example code]] [[Category:JavaScript example code]] [[Category:Example code]] [[Category:JavaScript example code]]

Revision as of 11:49, 9 August 2005

A common feature found in many extensions is to point the user to chrome:// URIs in a browser window (e.g., help or about information) or external (on-line http(s)://) HTML documents when he clicks an extension's button or link.

Rather than open a new browser or new tab each and every time the same URI is needed, it is better practice to re-use an existing tab which already displays the desired URI, if one exists. Following this practice minimizes the proliferation of tabs and browsers created by your extension. The following code demonstrates how to do this.

function openAndReuseOneTabPerURL(url) {
  var wm = Components.classes[";1"]
  var browserEnumerator = wm.getEnumerator("navigator:browser");

  // Check each browser instance for our URL
  var found = false;
  while (browserEnumerator.hasMoreElements() && !found) {
    var browserInstance = browserEnumerator.getNext();
    browserInstance = browserInstance.getBrowser();

    // Check each tab of this browser instance
    var index = 0, numTabs = browserInstance.mPanelContainer.childNodes.length;
    while (index < numTabs && !found) {
      var currentTab = browserInstance.getBrowserAtIndex(index);
      if (url == currentTab.currentURI.spec) {
        // The URL is already opened. Select its tab.
        browserInstance.selectedTab = currentTab;
        // Focus *this* browser
        found = true;

  // Our URL isn't open. Open it now.
  if (!found) {
    var recentWindow = wm.getMostRecentWindow("navigator:browser");
    if (recentWindow) {
      // Use an existing browser window
    else {
      // No browser windows are open, so open a new one.;

This code uses techniques discussed in Enumerating tabbrowser tabs and Opening a new browser window.