Firefox Extensions: Add Button to Nav Bar
Nov 2011
2
The new Add-On SDK for Firefox rocks! It is so easy to create and test using the cfx command line utility.
One thing that is conspicuously absent is the ability to add a button to the navigation toolbar. You know, the toolbar that holds the URL bar and bookmarks button. It took a fair amount of research and trial and error, but it turns out to be a small bit of code.
The code below should be placed in lib/main.js. It adds a button to the toolbar and removes it when the extension is disabled or uninstalled.
// import the modules we need var data = require('self').data; var {Cc, Ci} = require('chrome'); var mediator = Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator); // exports.main is called when extension is installed or re-enabled exports.main = function(options, callbacks) { addToolbarButton(); // do other stuff }; // exports.onUnload is called when Firefox starts and when the extension is disabled or uninstalled exports.onUnload = function(reason) { removeToolbarButton(); // do other stuff }; // add our button function addToolbarButton() { // this document is an XUL document var document = mediator.getMostRecentWindow('navigator:browser').document; var navBar = document.getElementById('nav-bar'); if (!navBar) { return; } var btn = document.createElement('toolbarbutton'); btn.setAttribute('id', 'mybutton-id'); btn.setAttribute('type', 'button'); // the toolbarbutton-1 class makes it look like a traditional button btn.setAttribute('class', 'toolbarbutton-1'); // the data.url is relative to the data folder btn.setAttribute('image', data.url('img/icon16.png')); btn.setAttribute('orient', 'horizontal'); // this text will be shown when the toolbar is set to text or text and iconss btn.setAttribute('label', 'My Button'); btn.addEventListener('click', function() { // do stuff, for example with tabs or pageMod }, false) navBar.appendChild(btn); } function removeToolbarButton() { // this document is an XUL document var document = mediator.getMostRecentWindow('navigator:browser').document; var navBar = document.getElementById('nav-bar'); var btn = document.getElementById('mybutton-id'); if (navBar && btn) { navBar.removeChild(btn); } }
6 comments

Move Add-ons around
A widget by definition
Make button draggable
cool but..
Working
reports: xpi can not be