Firefox Extensions: Add Button to Nav Bar

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

cool but..

Hey there tried out this snippet of code in the app builder beta and it didnt work. Just wanted to give you a heads up . Steps: 1. copied code in to main.js in add on builder 2. ran add on within add on builder. benji

Working

There may be some sort of error in the code above. However I just compiled a similar version of this code using cfx 1.4 for Firefox 9 and it works great.

reports: xpi can not be

reports: xpi can not be installed.