mozilla

Revision 482325 of Tabbed browser

  • Revision slug: Code_snippets/Tabbed_browser
  • Revision title: Anil
  • Revision id: 482325
  • Created:
  • Creator: anil_009
  • Is current revision? No
  • Comment

Revision Content

Here you should find a set of useful code snippets to help you work with Firefox's tabbed browser. The comments normally mark where you should be inserting your own code.

Each snippet normally includes some code to run at initialization, these are best run using a load listener. These snippets assume they are run in the context of a browser window. If you need to work with tabs from a non-browser window, you need to obtain a reference to one first, see Working with windows in chrome code for details.

Multiple meanings for the word 'browser'

The word 'browser' is used several ways. Of course the entire application Firefox is called "a browser". Within the Firefox browser are tabs and inside each tab is a browser, both in the common sense of a web page browser and the XUL sense of a {{ XULElem("browser") }} element. Furthermore another meaning of 'browser' in this document and in some Firefox source is "the tabbrowser element" in a Firefox XUL window.

Getting access to the browser

From main window

Code running in Firefox's global ChromeWindow, common for extensions that overlay into browser.xul, can access the {{ XULElem("tabbrowser") }} element using the global variable gBrowser.

// gBrowser is only accessible from the scope of 
// the browser window (browser.xul)
gBrowser.addTab(...);

If gBrowser isn't defined your code is either not running in the scope of the browser window or running too early. You can access gBrowser only after the browser window is fully loaded. If you need to do something with gBrowser right after the window is opened, listen for the load event and use gBrowser in the event listener.

If your code does not have access to the main window because it is run in a sidebar or dialog, you first need to get access to the browser window you need before you can use gBrowser. You can find more information on getting access to the browser window in Working with windows in chrome code.

From a sidebar

Basically, if your extension code is a sidebar you can use:

var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                       .getInterface(Components.interfaces.nsIWebNavigation)
                       .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                       .rootTreeItem
                       .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                       .getInterface(Components.interfaces.nsIDOMWindow);

mainWindow.gBrowser.addTab(...);

From a dialog

If your code is running in a dialog opened directly by a browser window, you can use:

window.opener.gBrowser.addTab(...);

If window.opener doesn't work, you can get the most recent browser window using this code:

var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var mainWindow = wm.getMostRecentWindow("navigator:browser");
mainWindow.gBrowser.addTab(...);

Opening a URL in a new tab

// Add tab  
gBrowser.addTab("http://www.google.com/");

// Add tab, then make active
gBrowser.selectedTab = gBrowser.addTab("http://www.google.com/");

Manipulating content of a new tab

If you want to work on the content of the newly opened tab, you'll need to wait until the content has finished loading.

// WRONG WAY (the page hasn't finished loading yet)
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/"));
alert(newTabBrowser.contentDocument.body.innerHTML);

// BETTER WAY
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/"));
newTabBrowser.addEventListener("load", function () {
  newTabBrowser.contentDocument.body.innerHTML = "<div>hello world</div>";
}, true);

(The event target in the onLoad handler will be a 'tab' XUL element). See tabbrowser for getBrowserForTab()

Opening a URL in the correct window/tab

There are methods available in chrome://browser/content/utilityOverlay.js that make it easy to open URL in tabs such as openUILinkIn and openUILink.

openUILinkIn( url, where, allowThirdPartyFixup, postData, referrerUrl )
where:
  • "current" current tab (if there aren't any browser windows, then in a new window instead)
  • "tab" new tab (if there aren't any browser windows, then in a new window instead)
  • "tabshifted" same as "tab" but in background if default is to select new tabs, and vice versa
  • "window" new window
  • "save" save to disk (with no filename hint!)
openUILink( url, e, ignoreButton, ignoreAlt, allowKeywordFixup, postData, referrerUrl )
 

The following code will open a URL in a new tab, an existing tab, or an existing window based on which mouse button was pressed and which hotkeys (ex: Ctrl) are being held. The code given is for a {{ XULElem("menuitem") }}, but will work equally well for other XUL elements. This will only work in an overlay of browser.xul.

XUL:

<menuitem oncommand="myExtension.foo(event)" onclick="checkForMiddleClick(this, event)" label="Click me"/>

JS:

var myExtension = {
  foo: function(event) {
    openUILink("http://www.example.com", event, false, true);
  }
}

Opening a URL in an on demand tab

var gSessionStore = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);

// Create new tab, but don't load the content.
var url = "https://developer.mozilla.org";
var tab = gBrowser.addTab(null);
gSessionStore.setTabState(tab,
  '{\
    "entries":[\
      {\
        "url":"' + url + '",\
        "title":"' + url + '"\
      }\
    ],\
    "lastAccessed":0,\
    "index":1,\
    "hidden":false,\
    "attributes":{},\
    "image":null\
  }'
);

Reusing tabs

Rather than open a new browser or new tab each and every time one is needed, it is good practice to try to re-use an existing tab which already displays the desired URL--if one is already open. Following this practice minimizes the proliferation of tabs and browsers created by your extension.

Reusing by URL/URI

A common feature found in many extensions is to point the user to chrome:// URIs in a browser window (for example, help or about information) or external (on-line http(s)://) HTML documents when the user clicks an extension's button or link. The following code demonstrates how to re-use an existing tab that already displays the desired URL/URI. If no such tab exists, a new one is opened with the specified URL/URI.

function openAndReuseOneTabPerURL(url) {
  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Components.interfaces.nsIWindowMediator);
  var browserEnumerator = wm.getEnumerator("navigator:browser");

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

    // Check each tab of this browser instance
    var numTabs = tabbrowser.browsers.length;
    for (var index = 0; index < numTabs; index++) {
      var currentBrowser = tabbrowser.getBrowserAtIndex(index);
      if (url == currentBrowser.currentURI.spec) {

        // The URL is already opened. Select this tab.
        tabbrowser.selectedTab = tabbrowser.tabContainer.childNodes[index];

        // Focus *this* browser-window
        browserWin.focus();

        found = true;
        break;
      }
    }
  }

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

Sometimes you want to reuse a previously-opened tab regardless of which URL/URI it displays. This assumes the tab is opened by your extension, not by some other browser component. We can do re-use an arbitrary tab by attaching a custom attribute to it when we first open it. Later, when we want to re-use that tab, we iterate over all open tabs looking for one which has our custom attribute. If such a tab exists, we change its URL/URI and focus/select it. If no such tab exists (perhaps the user closed it or we never opened it in the first place), we create a new tab with our custom attribute.

function openAndReuseOneTabPerAttribute(attrName, url) {
  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Components.interfaces.nsIWindowMediator);
  for (var found = false, index = 0, tabbrowser = wm.getEnumerator('navigator:browser').getNext().gBrowser;
       index < tabbrowser.tabContainer.childNodes.length && !found;
       index++) {

    // Get the next tab
    var currentTab = tabbrowser.tabContainer.childNodes[index];
  
    // Does this tab contain our custom attribute?
    if (currentTab.hasAttribute(attrName)) {

      // Yes--select and focus it.
      tabbrowser.selectedTab = currentTab;

      // Focus *this* browser window in case another one is currently focused
      tabbrowser.ownerDocument.defaultView.focus();
      found = true;
    }
  }

  if (!found) {
    // Our tab isn't open. Open it now.
    var browserEnumerator = wm.getEnumerator("navigator:browser");
    var tabbrowser = browserEnumerator.getNext().gBrowser;
  
    // Create tab
    var newTab = tabbrowser.addTab(url);
    newTab.setAttribute(attrName, "xyz");
  
    // Focus tab
    tabbrowser.selectedTab = newTab;
    
    // Focus *this* browser window in case another one is currently focused
    tabbrowser.ownerDocument.defaultView.focus();
  }
}

The function can be called like so:

openAndReuseOneTabPerAttribute("myextension-myattribute", "http://developer.mozilla.org/").

Closing a tab

This example closes the currently selected tab.

gBrowser.removeCurrentTab();

There is also a more generic removeTab method, which accepts a XUL {{ XULElem("tab") }} element as its single parameter.

Changing active tab

This moves one tab forward (to the right).

gBrowser.tabContainer.advanceSelectedTab(1, true);

This moves one tab to the left.

gBrowser.tabContainer.advanceSelectedTab(-1, true);

Detecting page load

See also Code snippets:On page load

function examplePageLoad(event) {
  if (event.originalTarget instanceof HTMLDocument) {
    var win = event.originalTarget.defaultView;
    if (win.frameElement) {
      // Frame within a tab was loaded. win should be the top window of
      // the frameset. If you don't want do anything when frames/iframes
      // are loaded in this web page, uncomment the following line:
      // return;
      // Find the root document:
      win = win.top;
    }
  }
}

// do not try to add a callback until the browser window has
// been initialised. We add a callback to the tabbed browser
// when the browser's window gets loaded.
window.addEventListener("load", function () {
  // Add a callback to be run every time a document loads.
  // note that this includes frames/iframes within the document
  gBrowser.addEventListener("load", examplePageLoad, true);
}, false);

...
// When no longer needed
gBrowser.removeEventListener("load", examplePageLoad, true);
...

Notification when a tab is added or removed

function exampleTabAdded(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been added
}

function exampleTabMoved(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been moved
}

function exampleTabRemoved(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been removed
}

// During initialization
var container = gBrowser.tabContainer;
container.addEventListener("TabOpen", exampleTabAdded, false);
container.addEventListener("TabMove", exampleTabMoved, false);
container.addEventListener("TabClose", exampleTabRemoved, false);

// When no longer needed
container.removeEventListener("TabOpen", exampleTabAdded, false);
container.removeEventListener("TabMove", exampleTabMoved, false);
container.removeEventListener("TabClose", exampleTabRemoved, false);

{{ gecko_callout_heading("1.9.1") }}

Starting in Gecko 1.9.1 {{ geckoRelease("1.9.1") }}, there's an easy way to listen on progress events on all tabs.

{{ h2_gecko_minversion("Notification when a tab's attributes change", "2.0") }}

Starting in Gecko 2.0, you can detect when a tab's attributes change by listening for the TabAttrModified event. The attributes to which changes result in this event being sent are:

  • {{ xulattr("label") }}
  • {{ xulattr("crop") }}
  • {{ xulattr("busy") }}
  • {{ xulattr("image") }}
  • {{ xulattr("selected") }}
function exampleTabAttrModified(event) {
  var tab = event.target;
  // Now you can check what's changed on the tab
}

// During initialization
var container = gBrowser.tabContainer;
container.addEventListener("TabAttrModified", exampleTabAttrModified, false);

// When no longer needed
container.removeEventListener("TabAttrModified", exampleTabAttrModified, false);

{{ h2_gecko_minversion("Notification when a tab is pinned or unpinned", "2.0") }}

Starting in Gecko 2.0, tabs can be "pinned"; that is, they become special application tabs ("app tabs"), which are pinned to the beginning of the tab bar, and show only the favicon. You can detect when a tab becomes pinned or unpinned by watching for the TabPinned and TabUnpinned events.

function exampleTabPinned(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been pinned
}

function exampleTabUnpinned(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been pinned
}

// Initialization

var container = gBrowser.tabContainer;
container.addEventListener("TabPinned", exampleTabPinned, false);
container.addEventListener("TabUnpinned", exampleTabUnpinned, false);

// When no longer needed

container.removeEventListener("TabPinned", exampleTabPinned, false);
container.removeEventListener("TabUnpinned", exampleTabUnpinned, false);

Detecting tab selection

The following code allows you to detect when a new tab is selected in the browser:

function exampleTabSelected(event) {
  var browser = gBrowser.selectedBrowser;
  // browser is the XUL element of the browser that's just been selected
}

// During initialisation
var container = gBrowser.tabContainer;
container.addEventListener("TabSelect", exampleTabSelected, false);

// When no longer needed
container.removeEventListener("TabSelect", exampleTabSelected, false);

Getting document of currently selected tab

The following code allows you to retrieve the document that is in the selected tab. This code will work in the scope of the browser window (e.g. you're working from an overlay to the browser window).

gBrowser.contentDocument;

or

content.document

If you're working from a window or dialog that was opened by the browser window, you can use this code to get the document displayed in the selected tab in the browser window that opened the new window or dialog.

window.opener.content.document

From windows or dialogs not opened by the browser window, you can use {{ interface("nsIWindowMediator") }} to get the document displayed in the selected tab of the most recently used browser window.

var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var recentWindow = wm.getMostRecentWindow("navigator:browser");
return recentWindow ? recentWindow.content.document.location : null;

See also Working with windows in chrome code.

Enumerating browsers

To go through all browser in a tabbrowser, first get a reference to a browser's window. If your code is executed from a Firefox browser.xul overlay (for example, it is a toolbar button or menu click handler), you can access the current window with the window pre-defined variable. However, if your code is executed from its own window (for example, a settings/options dialog), you can use {{ interface("nsIWindowMediator") }} to get a browser's window.

Next, get the <tabbrowser/> element. You can get it with win.gBrowser, where win is the browser's window from the previous step. You can use simply gBrowser instead of window.gBrowser if running in the context of a browser.xul overlay.

Finally, use gBrowser.browsers.length to get the number of browsers and gBrowser.getBrowserAtIndex() to get a <browser/> element. For example:

var num = gBrowser.browsers.length;
for (var i = 0; i < num; i++) {
  var b = gBrowser.getBrowserAtIndex(i);
  try {
    dump(b.currentURI.spec); // dump URLs of all open tabs to console
  } catch(e) {
    Components.utils.reportError(e);
  }
}

To learn what methods are available for <browser/> and <tabbrowser/> elements, use DOM Inspector or look in {{ source("toolkit/content/widgets/browser.xml","browser.xml") }} for corresponding XBL bindings (or just look at the current reference pages on {{ XULElem("browser") }} and {{ XULElem("tabbrowser") }}.

Getting the browser that fires the http-on-modify-request notification

See the Observer notifications page for information on http-on-* notifications.

Note that some HTTP requests aren't associated with a tab; for example, RSS feed updates, extension manager requests, XHR requests from XPCOM components, etc. In those cases, the following code returns null.

Warning: This code should be updated to use {{interface("nsILoadContext")}} instead of getInterface(Components.interfaces.nsIDOMWindow), see this example.
observe: function (subject, topic, data) {
  if (topic == "http-on-modify-request") {
    subject.QueryInterface(Components.interfaces.nsIHttpChannel);
    var url = subject.URI.spec; /* url being requested. you might want this for something else */
    var browser = this.getBrowserFromChannel(subject);
    if (browser != null) {
      /* do something */
    }
  }
},

getBrowserFromChannel: function (aChannel) {
  try {
    var notificationCallbacks = 
      aChannel.notificationCallbacks ? aChannel.notificationCallbacks : aChannel.loadGroup.notificationCallbacks;

    if (!notificationCallbacks)
      return null;

    var domWin = notificationCallbacks.getInterface(Components.interfaces.nsIDOMWindow);
    return gBrowser.getBrowserForDocument(domWin.top.document);
  }
  catch (e) {
    dump(e + "\n");
    return null;
  }
}

{{ languages( { "fr": "fr/Extraits_de_code/Onglets_de_navigation", "ja": "ja/Code_snippets/Tabbed_browser", "pl": "pl/Fragmenty_kodu/Przegl\u0105danie_w_kartach" } ) }}

Revision Source

<p>Here you should find a set of useful code snippets to help you work with Firefox's tabbed browser. The comments normally mark where you should be inserting your own code.</p>
<p>Each snippet normally includes some code to run at initialization, these are best run using a <a href="/en/Extension_Frequently_Asked_Questions#Why_doesn.27t_my_script_run_properly.3F" title="en/Extension_Frequently_Asked_Questions#Why_doesn.27t_my_script_run_properly.3F">load listener</a>. These snippets assume they are run in the context of a browser window. If you need to work with tabs from a non-browser window, you need to obtain a reference to one first, see <a href="/en/Working_with_windows_in_chrome_code" title="en/Working_with_windows_in_chrome_code">Working with windows in chrome code</a> for details.</p>
<h3 id="Getting_access_to_the_browser" name="Getting_access_to_the_browser">Multiple meanings for the word 'browser'</h3>
<p>The word 'browser' is used several ways. Of course the entire application Firefox is called "a browser". Within the Firefox browser are tabs and inside each tab is a browser, both in the common sense of a web page browser and the XUL sense of a {{ XULElem("browser") }} element. Furthermore another meaning of 'browser' in this document and in some Firefox source is "the <a href="/en-US/docs/XUL/tabbrowser" title="/en-US/docs/XUL/tabbrowser">tabbrowser</a> element" in a Firefox XUL window.</p>
<h3 id="Getting_access_to_the_browser" name="Getting_access_to_the_browser">Getting access to the browser</h3>
<h4 id="From_main_window">From main window</h4>
<p>Code running in Firefox's global ChromeWindow, common for extensions that overlay into <code>browser.xul</code>, can access the {{ XULElem("tabbrowser") }} element using the global variable <code>gBrowser.</code></p>
<pre class="eval">
// gBrowser is only accessible from the scope of 
// the browser window (browser.xul)
gBrowser.addTab(...);
</pre>
<p>If <code>gBrowser</code> isn't defined your code is either not running in the scope of the browser window or running too early. You can access <code>gBrowser</code> only after the browser window is fully loaded. If you need to do something with <code>gBrowser</code> right after the window is opened, <a href="/en/DOM/element.addEventListener" title="en/DOM/element.addEventListener">listen</a> for the <code>load</code> event and use <code>gBrowser</code> in the event listener.</p>
<p>If your code does not have access to the main window because it is run in a sidebar or dialog, you first need to get access to the browser window you need before you can use <code>gBrowser</code>. You can find more information on getting access to the browser window in <a href="/en/Working_with_windows_in_chrome_code" title="en/Working_with_windows_in_chrome_code">Working with windows in chrome code</a>.</p>
<h4 id="From_a_sidebar">From a sidebar</h4>
<p>Basically, if your extension code is a sidebar you can use:</p>
<pre class="brush: js">
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                       .getInterface(Components.interfaces.nsIWebNavigation)
                       .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                       .rootTreeItem
                       .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                       .getInterface(Components.interfaces.nsIDOMWindow);

mainWindow.gBrowser.addTab(...);
</pre>
<h4 id="From_a_dialog">From a dialog</h4>
<p>If your code is running in a dialog opened directly by a browser window, you can use:</p>
<pre class="eval">
window.opener.gBrowser.addTab(...);
</pre>
<p>If <code>window.opener</code> doesn't work, you can get the most recent browser window using this code:</p>
<pre class="brush: js">
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var mainWindow = wm.getMostRecentWindow("navigator:browser");
mainWindow.gBrowser.addTab(...);
</pre>
<h3 id="Opening_a_URL_in_a_new_tab" name="Opening_a_URL_in_a_new_tab">Opening a URL in a new tab</h3>
<pre class="brush: js">
// Add tab  
gBrowser.addTab("http://www.google.com/");

// Add tab, then make active
gBrowser.selectedTab = gBrowser.addTab("http://www.google.com/");
</pre>
<h4 id="Manipulating_content_of_a_new_tab" name="Manipulating_content_of_a_new_tab">Manipulating content of a new tab</h4>
<p>If you want to work on the content of the newly opened tab, you'll need to wait until the content has finished loading.</p>
<pre class="brush: js">
// WRONG WAY (the page hasn't finished loading yet)
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/"));
alert(newTabBrowser.contentDocument.body.innerHTML);

// BETTER WAY
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/"));
newTabBrowser.addEventListener("load", function () {
  newTabBrowser.contentDocument.body.innerHTML = "&lt;div&gt;hello world&lt;/div&gt;";
}, true);
</pre>
<p>(The event target in the onLoad handler will be a 'tab' XUL element). See <a href="/en/XUL/tabbrowser#m-getBrowserForTab" title="en/XUL/tabbrowser#m-getBrowserForTab">tabbrowser</a> for getBrowserForTab()</p>
<h4 id="Opening_a_URL_in_the_correct_window.2Ftab" name="Opening_a_URL_in_the_correct_window.2Ftab">Opening a URL in the correct window/tab</h4>
<p>There are methods available in <code><a class="external" href="http://mxr.mozilla.org/mozilla-central/source/browser/base/content/utilityOverlay.js" rel="external nofollow" target="_blank" title="http://mxr.mozilla.org/mozilla-central/source/browser/base/content/utilityOverlay.js">chrome://browser/content/utilityOverlay.js</a></code> that make it easy to open URL in tabs such as <code>openUILinkIn</code> and <code>openUILink</code>.</p>
<dl>
  <dt>
    <code>openUILinkIn( url, where, allowThirdPartyFixup, postData, referrerUrl ) </code></dt>
  <dd>
    where:
    <ul>
      <li>"current" current tab (if there aren't any browser windows, then in a new window instead)</li>
      <li>"tab" new tab (if there aren't any browser windows, then in a new window instead)</li>
      <li>"tabshifted" same as "tab" but in background if default is to select new tabs, and vice versa</li>
      <li>"window" new window</li>
      <li>"save" save to disk (with no filename hint!)</li>
    </ul>
  </dd>
  <dt>
    <code>openUILink( url, e, ignoreButton, ignoreAlt, allowKeywordFixup, postData, referrerUrl ) </code></dt>
  <dd>
    &nbsp;</dd>
</dl>
<p>The following code will open a URL in a new tab, an existing tab, or an existing window based on which mouse button was pressed and which hotkeys (ex: Ctrl) are being held. The code given is for a {{ XULElem("menuitem") }}, but will work equally well for other XUL elements. This will only work in an overlay of browser.xul.</p>
<p>XUL:</p>
<pre class="eval">
&lt;menuitem oncommand="myExtension.foo(event)" onclick="checkForMiddleClick(this, event)" label="Click me"/&gt;
</pre>
<p>JS:</p>
<pre class="brush: js">
var myExtension = {
  foo: function(event) {
    openUILink("http://www.example.com", event, false, true);
  }
}</pre>
<h4 id="Opening_a_URL_in_an_on_demand_tab">Opening a URL in an on demand tab</h4>
<pre class="brush: js">
var gSessionStore = Cc["@mozilla.org/browser/sessionstore;1"].getService(Ci.nsISessionStore);

// Create new tab, but don't load the content.
var url = "https://developer.mozilla.org";
var tab = gBrowser.addTab(null);
gSessionStore.setTabState(tab,
  '{\
&nbsp;   "entries":[\
&nbsp;&nbsp;&nbsp;   {\
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   "url":"' + url + '",\
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "title":"' + url + '"\
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }\
&nbsp;&nbsp;&nbsp; ],\
&nbsp;&nbsp;&nbsp; "lastAccessed":0,\
&nbsp;&nbsp;&nbsp; "index":1,\
&nbsp;&nbsp;&nbsp; "hidden":false,\
&nbsp;&nbsp;&nbsp; "attributes":{},\
&nbsp;&nbsp;&nbsp; "image":null\
&nbsp; }'
);
</pre>
<h4 id="Reusing_tabs" name="Reusing_tabs">Reusing tabs</h4>
<p>Rather than open a new browser or new tab each and every time one is needed, it is good practice to try to re-use an existing tab which already displays the desired URL--if one is already open. Following this practice minimizes the proliferation of tabs and browsers created by your extension.</p>
<h5 id="Reusing_by_URL.2FURI" name="Reusing_by_URL.2FURI">Reusing by URL/URI</h5>
<p>A common feature found in many extensions is to point the user to <code>chrome://</code> URIs in a browser window (for example, help or about information) or external (on-line <code>http(s)://</code>) HTML documents when the user clicks an extension's button or link. The following code demonstrates how to re-use an existing tab that already displays the desired URL/URI. If no such tab exists, a new one is opened with the specified URL/URI.</p>
<pre class="brush: js">
function openAndReuseOneTabPerURL(url) {
  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Components.interfaces.nsIWindowMediator);
  var browserEnumerator = wm.getEnumerator("navigator:browser");

  // Check each browser instance for our URL
  var found = false;
  while (!found &amp;&amp; browserEnumerator.hasMoreElements()) {
    var browserWin = browserEnumerator.getNext();
    var tabbrowser = browserWin.gBrowser;

    // Check each tab of this browser instance
    var numTabs = tabbrowser.browsers.length;
    for (var index = 0; index &lt; numTabs; index++) {
      var currentBrowser = tabbrowser.getBrowserAtIndex(index);
      if (url == currentBrowser.currentURI.spec) {

        // The URL is already opened. Select this tab.
        tabbrowser.selectedTab = tabbrowser.tabContainer.childNodes[index];

        // Focus *this* browser-window
        browserWin.focus();

        found = true;
        break;
      }
    }
  }

  // Our URL isn't open. Open it now.
  if (!found) {
    var recentWindow = wm.getMostRecentWindow("navigator:browser");
    if (recentWindow) {
      // Use an existing browser window
      recentWindow.delayedOpenTab(url, null, null, null, null);
    }
    else {
      // No browser windows are open, so open a new one.
      window.open(url);
    }
  }
}
</pre>
<h5 id="Reusing_by_other_criteria" name="Reusing_by_other_criteria">Reusing by other criteria</h5>
<p>Sometimes you want to reuse a previously-opened tab regardless of which URL/URI it displays. This assumes the tab is opened by your extension, not by some other browser component. We can do re-use an arbitrary tab by attaching a custom attribute to it when we first open it. Later, when we want to re-use that tab, we iterate over all open tabs looking for one which has our custom attribute. If such a tab exists, we change its URL/URI and focus/select it. If no such tab exists (perhaps the user closed it or we never opened it in the first place), we create a new tab with our custom attribute.</p>
<pre class="brush: js">
function openAndReuseOneTabPerAttribute(attrName, url) {
  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Components.interfaces.nsIWindowMediator);
  for (var found = false, index = 0, tabbrowser = wm.getEnumerator('navigator:browser').getNext().gBrowser;
       index &lt; tabbrowser.tabContainer.childNodes.length &amp;&amp; !found;
       index++) {

    // Get the next tab
    var currentTab = tabbrowser.tabContainer.childNodes[index];
  
    // Does this tab contain our custom attribute?
    if (currentTab.hasAttribute(attrName)) {

      // Yes--select and focus it.
      tabbrowser.selectedTab = currentTab;

      // Focus *this* browser window in case another one is currently focused
      tabbrowser.ownerDocument.defaultView.focus();
      found = true;
    }
  }

  if (!found) {
    // Our tab isn't open. Open it now.
    var browserEnumerator = wm.getEnumerator("navigator:browser");
    var tabbrowser = browserEnumerator.getNext().gBrowser;
  
    // Create tab
    var newTab = tabbrowser.addTab(url);
    newTab.setAttribute(attrName, "xyz");
  
    // Focus tab
    tabbrowser.selectedTab = newTab;
    
    // Focus *this* browser window in case another one is currently focused
    tabbrowser.ownerDocument.defaultView.focus();
  }
}
</pre>
<p>The function can be called like so:</p>
<pre class="eval">
<span class="nowiki">openAndReuseOneTabPerAttribute("myextension-myattribute", "http://developer.mozilla.org/")</span>.
</pre>
<h3 id="Closing_a_tab" name="Closing_a_tab">Closing a tab</h3>
<p>This example closes the currently selected tab.</p>
<pre class="eval">
gBrowser.removeCurrentTab();
</pre>
<p>There is also a more generic <code>removeTab</code> method, which accepts a XUL {{ XULElem("tab") }} element as its single parameter.</p>
<h3 id="Changing_active_tab" name="Changing_active_tab">Changing active tab</h3>
<p>This moves one tab forward (to the right).</p>
<pre>
gBrowser.tabContainer.advanceSelectedTab(1, true);
</pre>
<p>This moves one tab to the left.</p>
<pre>
gBrowser.tabContainer.advanceSelectedTab(-1, true);
</pre>
<h3 id="Detecting_page_load" name="Detecting_page_load">Detecting page load</h3>
<p>See also <a href="/en/Code_snippets/On_page_load" title="en/Code_snippets/On_page_load">Code snippets:On page load</a></p>
<pre class="brush: js">
function examplePageLoad(event) {
  if (event.originalTarget instanceof HTMLDocument) {
    var win = event.originalTarget.defaultView;
    if (win.frameElement) {
      // Frame within a tab was loaded. win should be the top window of
      // the frameset. If you don't want do anything when frames/iframes
      // are loaded in this web page, uncomment the following line:
      // return;
      // Find the root document:
      win = win.top;
    }
  }
}

// do not try to add a callback until the browser window has
// been initialised. We add a callback to the tabbed browser
// when the browser's window gets loaded.
window.addEventListener("load", function () {
  // Add a callback to be run every time a document loads.
  // note that this includes frames/iframes within the document
  gBrowser.addEventListener("load", examplePageLoad, true);
}, false);

...
// When no longer needed
gBrowser.removeEventListener("load", examplePageLoad, true);
...
</pre>
<h3 id="Notification_when_a_tab_is_added_or_removed" name="Notification_when_a_tab_is_added_or_removed">Notification when a tab is added or removed</h3>
<pre class="brush: js">
function exampleTabAdded(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been added
}

function exampleTabMoved(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been moved
}

function exampleTabRemoved(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been removed
}

// During initialization
var container = gBrowser.tabContainer;
container.addEventListener("TabOpen", exampleTabAdded, false);
container.addEventListener("TabMove", exampleTabMoved, false);
container.addEventListener("TabClose", exampleTabRemoved, false);

// When no longer needed
container.removeEventListener("TabOpen", exampleTabAdded, false);
container.removeEventListener("TabMove", exampleTabMoved, false);
container.removeEventListener("TabClose", exampleTabRemoved, false);
</pre>
<div class="geckoVersionNote">
  <p>{{ gecko_callout_heading("1.9.1") }}</p>
  <p>Starting in Gecko 1.9.1 {{ geckoRelease("1.9.1") }}, there's an easy way to <a href="/En/Listening_to_events_on_all_tabs" title="https://developer.mozilla.org/en/Listening_to_events_on_all_tabs">listen on progress events on all tabs</a>.</p>
</div>
<p>{{ h2_gecko_minversion("Notification when a tab's attributes change", "2.0") }}</p>
<p>Starting in Gecko 2.0, you can detect when a tab's attributes change by listening for the <code>TabAttrModified</code> event. The attributes to which changes result in this event being sent are:</p>
<ul>
  <li>{{ xulattr("label") }}</li>
  <li>{{ xulattr("crop") }}</li>
  <li>{{ xulattr("busy") }}</li>
  <li>{{ xulattr("image") }}</li>
  <li>{{ xulattr("selected") }}</li>
</ul>
<pre class="brush: js">
function exampleTabAttrModified(event) {
  var tab = event.target;
  // Now you can check what's changed on the tab
}

// During initialization
var container = gBrowser.tabContainer;
container.addEventListener("TabAttrModified", exampleTabAttrModified, false);

// When no longer needed
container.removeEventListener("TabAttrModified", exampleTabAttrModified, false);
</pre>
<p>{{ h2_gecko_minversion("Notification when a tab is pinned or unpinned", "2.0") }}</p>
<p>Starting in Gecko 2.0, tabs can be "pinned"; that is, they become special application tabs ("app tabs"), which are pinned to the beginning of the tab bar, and show only the favicon. You can detect when a tab becomes pinned or unpinned by watching for the <code>TabPinned</code> and <code>TabUnpinned</code> events.</p>
<pre class="brush: js">
function exampleTabPinned(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been pinned
}

function exampleTabUnpinned(event) {
  var browser = gBrowser.getBrowserForTab(event.target);
  // browser is the XUL element of the browser that's been pinned
}

// Initialization

var container = gBrowser.tabContainer;
container.addEventListener("TabPinned", exampleTabPinned, false);
container.addEventListener("TabUnpinned", exampleTabUnpinned, false);

// When no longer needed

container.removeEventListener("TabPinned", exampleTabPinned, false);
container.removeEventListener("TabUnpinned", exampleTabUnpinned, false);
</pre>
<h3 id="Detecting_tab_selection" name="Detecting_tab_selection">Detecting tab selection</h3>
<p>The following code allows you to detect when a new tab is selected in the browser:</p>
<pre class="brush: js">
function exampleTabSelected(event) {
  var browser = gBrowser.selectedBrowser;
  // browser is the XUL element of the browser that's just been selected
}

// During initialisation
var container = gBrowser.tabContainer;
container.addEventListener("TabSelect", exampleTabSelected, false);

// When no longer needed
container.removeEventListener("TabSelect", exampleTabSelected, false);
</pre>
<h3 id="Getting_document_of_currently_selected_tab" name="Getting_document_of_currently_selected_tab">Getting document of currently selected tab</h3>
<p>The following code allows you to retrieve the document that is in the selected tab. This code will work in the scope of the browser window (e.g. you're working from an overlay to the browser window).</p>
<pre class="eval">
gBrowser.contentDocument;
</pre>
<p>or</p>
<pre class="eval">
content.document
</pre>
<p>If you're working from a window or dialog that was opened by the browser window, you can use this code to get the document displayed in the selected tab in the browser window that opened the new window or dialog.</p>
<pre class="eval">
window.opener.content.document
</pre>
<p>From windows or dialogs not opened by the browser window, you can use {{ interface("nsIWindowMediator") }} to get the document displayed in the selected tab of the most recently used browser window.</p>
<pre class="brush: js">
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Components.interfaces.nsIWindowMediator);
var recentWindow = wm.getMostRecentWindow("navigator:browser");
return recentWindow ? recentWindow.content.document.location : null;
</pre>
<p>See also <a href="/en/Working_with_windows_in_chrome_code#Content_windows" title="en/Working_with_windows_in_chrome_code#Content_windows">Working with windows in chrome code</a>.</p>
<h3 id="Enumerating_tabs" name="Enumerating_tabs">Enumerating browsers</h3>
<p>To go through all browser in a tabbrowser, first get a reference to a browser's window. If your code is executed from a Firefox <code>browser.xul</code> overlay (for example, it is a toolbar button or menu <em>click</em> handler), you can access the current window with the <code>window</code> pre-defined variable. However, if your code is executed from its own window (for example, a settings/options dialog), you can use {{ interface("nsIWindowMediator") }} to get a browser's window.</p>
<p>Next, get the <code>&lt;tabbrowser/&gt;</code> element. You can get it with <code>win.gBrowser</code>, where <code>win</code> is the browser's window from the previous step. You can use simply <code>gBrowser</code> instead of <code>window.gBrowser</code> if running in the context of a <code>browser.xul</code> overlay.</p>
<p>Finally, use <code>gBrowser.browsers.length</code> to get the number of browsers and <code>gBrowser.getBrowserAtIndex()</code> to get a <code>&lt;browser/&gt;</code> element. For example:</p>
<pre class="brush: js">
var num = gBrowser.browsers.length;
for (var i = 0; i &lt; num; i++) {
  var b = gBrowser.getBrowserAtIndex(i);
  try {
    dump(b.currentURI.spec); // dump URLs of all open tabs to console
  } catch(e) {
    Components.utils.reportError(e);
  }
}</pre>
<p>To learn what methods are available for <code>&lt;browser/&gt;</code> and <code>&lt;tabbrowser/&gt;</code> elements, use <a href="/en/DOM_Inspector" title="en/DOM_Inspector">DOM Inspector</a> or look in {{ source("toolkit/content/widgets/browser.xml","browser.xml") }} for corresponding XBL bindings (or just look at the current reference pages on {{ XULElem("browser") }} and {{ XULElem("tabbrowser") }}.</p>
<h3 id="Getting_the_browser_that_fires_the_http-on-modify-request_notification">Getting the browser that fires the http-on-modify-request notification</h3>
<p>See the <a href="/en/Observer_Notifications#HTTP_requests" title="en/Observer_Notifications#HTTP_requests">Observer notifications</a> page for information on http-on-* notifications.</p>
<p>Note that some HTTP requests aren't associated with a tab; for example, RSS feed updates, extension manager requests, XHR requests from XPCOM components, etc. In those cases, the following code returns null.</p>
<div class="warning">
  <strong>Warning:</strong> This code should be updated to use {{interface("nsILoadContext")}} instead of <code>getInterface(Components.interfaces.nsIDOMWindow)</code>, <a href="/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request" title="/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request">see this example</a>.</div>
<pre class="brush: js">
observe: function (subject, topic, data) {
  if (topic == "http-on-modify-request") {
    subject.QueryInterface(Components.interfaces.nsIHttpChannel);
    var url = subject.URI.spec; /* url being requested. you might want this for something else */
    var browser = this.getBrowserFromChannel(subject);
    if (browser != null) {
      /* do something */
    }
  }
},

getBrowserFromChannel: function (aChannel) {
  try {
    var notificationCallbacks = 
      aChannel.notificationCallbacks ? aChannel.notificationCallbacks : aChannel.loadGroup.notificationCallbacks;

    if (!notificationCallbacks)
      return null;

    var domWin = notificationCallbacks.getInterface(Components.interfaces.nsIDOMWindow);
    return gBrowser.getBrowserForDocument(domWin.top.document);
  }
  catch (e) {
    dump(e + "\n");
    return null;
  }
}
</pre>
<p>{{ languages( { "fr": "fr/Extraits_de_code/Onglets_de_navigation", "ja": "ja/Code_snippets/Tabbed_browser", "pl": "pl/Fragmenty_kodu/Przegl\u0105danie_w_kartach" } ) }}</p>
Revert to this revision