Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Adding a toolbar button

There are two tutorials available:

  • An elaborate step by step tutorial for beginners: Custom Toolbar Button
  • A tutorial describing the steps needed to add a toolbar button assuming you already have a working extension and know the basics of extension development: Creating toolbar buttons

Adding button by default

When you create and deploy your extension and include a toolbar button for it by overlaying the Customize toolbarpalette, it is not available by default. The user has to drag it onto the toolbar. The following code will place your button on the toolbar by default. This should only be done on the first run of your add-on after installation so that if the user decides to remove your button, it doesn't show up again every time they start the application.

Notes

  • Insert your button by default only once, at first run, or when an extension update adds a new button.
  • Please only add your button by default if it adds real value to the user and will be a frequent entry point to your extension.
  • You must not insert your toolbar button between any of the following elements: the combined back/forward button, the location bar, the stop botton, or the reload button. These elements have special behaviors when placed next to eachother, and will break if separated by another element.
/**
 * Installs the toolbar button with the given ID into the given
 * toolbar, if it is not already present in the document.
 *
 * @param {string} toolbarId The ID of the toolbar to install to.
 * @param {string} id The ID of the button to install.
 * @param {string} afterId The ID of the element to insert after. @optional
 */
function installButton(toolbarId, id, afterId) {
    if (!document.getElementById(id)) {
        var toolbar = document.getElementById(toolbarId);

        // If no afterId is given, then append the item to the toolbar
        var before = null;
        if (afterId) {
            let elem = document.getElementById(afterId);
            if (elem && elem.parentNode == toolbar)
                before = elem.nextElementSibling;
        }

        toolbar.insertItem(id, before);
        toolbar.setAttribute("currentset", toolbar.currentSet);
        document.persist(toolbar.id, "currentset");

        if (toolbarId == "addon-bar")
            toolbar.collapsed = false;
    }
}

if (firstRun) {
    installButton("nav-bar", "my-extension-navbar-button");
    // The "addon-bar" is available since Firefox 4
    installButton("addon-bar", "my-extension-addon-bar-button");
}

See also

Document Tags and Contributors

 Last updated by: mlissner,