Przeglądanie w kartach

UWAGA: Tłumaczenie tej strony nie zostało zakończone.
Może być ona niekompletna lub wymagać korekty.
Chcesz pomóc? | Dokończ tłumaczenie | Sprawdź ortografię | Więcej takich stron+.
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 Praca z oknami w kodzie chrome for details.

Note that Firefox 2 has made detecting changes to the tabs far easier, if you are only developing for Firefox 2 and greater you should use the examples for that. The examples for Firefox 1.5 and lower will usually work OK on Firefox 2.

See also the XUL tabbrowser element reference. gBrowser object (same as getBrowser()) is a tabbrowser element.

Getting access to the browser

The browser is a tabbrowser element located in the main window of the application (browser.xul for Firefox). Code running in a browser window, common for extensions that overlay into browser.xul, can access the browser using either the global variable gBrowser or the function getBrowser().

// gBrowser/getBrowser() is only accessible from the scope of 
// the browser window (browser.xul)
gBrowser.addTab(...);
getBrowser().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.

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.getBrowser().addTab(...);

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

window.opener.getBrowser().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.getBrowser().addTab(...);

Opening a new tab

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

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

Opening a URL in the correct window/tab

This 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 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);
  }
}

Closing a tab

This example closes the currently selected tab.

gBrowser.removeCurrentTab();

There is also a more generic removeTab method, which accepts a XUL tab element as its single parameter.

Changing active tab

This moves one tab forward (to the right).

gBrowser.mTabContainer.advanceSelectedTab(1, true);

This moves one tab to the left.

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

Detecting page load

function examplePageLoad(event)
{
  if (event.originalTarget instanceof HTMLDocument) {
    var doc = event.originalTarget;
    if (event.originalTarget.defaultView.frameElement) {
      // Frame within a tab was loaded. doc should be the root document 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:
      while (doc.defaultView.frameElement) {
        doc=doc.defaultView.frameElement.ownerDocument;
      }
    }
  }
}

// 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 (<= Firefox 1.5)

function exampleTabAdded(event)
{ // listening for new tabs
  if (event.relatedNode != gBrowser.mPanelContainer)
    return; //Could be anywhere in the DOM (unless bubbling is caught at the interface?)

  var browser;
  if (event.target.localName == "browser") // SeaMonkey
    browser = event.target;
  else if (event.target.localName == "vbox") // Firefox
    browser = event.target.childNodes[1];
  // browser is the XUL element of the browser that's been added
}

function exampleTabRemoved(event)
{
  if (event.relatedNode != gBrowser.mPanelContainer)
    return;

  var browser;
  if (event.target.localName == "browser") // SeaMonkey
    browser = event.target;
  else if (event.target.localName == "vbox") // Firefox
    browser = event.target.childNodes[1];
  // browser is the XUL element of the browser that's been removed
}

// During initialisation
var container = gBrowser.mPanelContainer;
container.addEventListener("DOMNodeInserted", exampleTabAdded, false);
container.addEventListener("DOMNodeRemoved", exampleTabRemoved, false);

// When no longer needed
container.removeEventListener("DOMNodeInserted", exampleTabAdded, false);
container.removeEventListener("DOMNodeRemoved", exampleTabRemoved, false);

Notification when a tab is added or removed (Firefox 2+)

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

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

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

// During initialisation
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);

Detecting tab selection (<= Firefox 1.5)

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

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

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

// When no longer needed
var container = gBrowser.mPanelContainer;
container.removeEventListener("select", exampleTabSelected, false);

Detecting tab selection (Firefox 2+)

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

function exampleTabSelected(event)
{
  var browser = gBrowser.selectedTab.linkedBrowser;
  // 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.selectedBrowser.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 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 tabs

To go through all open tabs in a browser, 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 nsIWindowMediator to get a browser's window.</li>

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 open tabs 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 browser.xml and tabbrowser.xml for corresponding XBL bindings.

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 (e.g., 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 browserInstance = browserEnumerator.getNext().getBrowser();

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

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

        // Focus *this* browser
        browserInstance.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, browserInstance = wm.getEnumerator('navigator:browser').getNext().getBrowser();
       index < browserInstance.mTabContainer.childNodes.length && !found;
       index++) {

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

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

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

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

The function can be called like so:

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

Autorzy i etykiety dokumentu

Autorzy tej strony: Ptak82, splewako
Ostatnia aktualizacja: splewako,