From MozillaWiki
< Mobile‎ | Fennec
Jump to: navigation, search

Here you should find a set of useful code snippets to help you work with Fennec. Although Fennec is built on XUL and JS, like Firefox, the architecture between Firefox and Fennec is different.

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.

Load Listener

You can't usually just run UI code as global code in your JavaScript. You need to wait for the XUL window to finish loading before trying to access any XUL elements.

window.addEventListener("load", startup, true);
function startup() {
  // access UI elements here

Access the Browser

Fennec has several JavaScript objects you should use to access the browser and the browser UI. The main objects are Browser and Tab. They have the following APIs:

  property browsers
    gets an array of all XUL browsers.
  property selectedBrowser
    gets the currently active XUL browser.
  function getTabAtIndex(index)
    returns Tab or null.
  function getTabFromContent(content)
    returns Tab or null.
  function addTab(uri, bringFront)
    creates a new Tab with the given URI. returns the new Tab.
  function closeTab(tab)
    closes the given Tab.
  property selectedTab
    sets/gets the selected Tab.

  property browser
    gets the XUL browser for the Tab

Listening for Browser Events

Detecting XUL browser load and unload events, as well as any others, is pretty easy to do. It's the same as in Firefox, but you use a different root container element:

function startup() {
  let browsers = document.getElementById("browsers");
  browsers.addEventListener("load", onWebPageLoad, true);

function onWebPageLoad(event) {
  if (event.originalTarget instanceof HTMLDocument) {
    let htmldoc = event.originalTarget;
    // use the document

Listening for Tab Events

The Browser fires a few Tab-specific events. You can use these events to monitor tab browser lifecycle: TabOpen, TabSelect, and TabClose. Here's an example of hooking up listeners for the events:

function startup() {
  let tabs = document.getElementById("tabs");
  tabs.addEventListener("TabOpen", onTabOpen, true);

function onTabOpen(event) {
  let newTab = event.originalTarget;