Develop a Firefox Addon using the Addon SDK

2015-02-21 13:44

Today I found myself in need of a Firefox addon for Archive.Today but could not find a suitable one on the Add-ons site. Naturally I thought I'd write one myself.

Everything written here is based on instructions found on the Add-on SDK site.

Install the Add-On SDK

curl -O https://ftp.mozilla.org/pub/mozilla.org/labs/jetpack/addon-sdk-1.17.tar.gz
tar -xf addon-sdk-1.17.tar.gz
cd addon-sdk-1.17
source bin/activate

The SDK makes use of Python and virtualenv and the last line, source bin/active, is used to activate the environment. This must be done each time you want to use the SDK.

The primary interface to the addon SDK is the cfx command line tool. To verify the installation and activation you can run it without arguments and it should respone with some information on its use:

cfx

Create an Add-On

mkdir add-to-archive-today
cd add-to-archive-today
cfx init

This creates the scaffolding for my addon. Now let's add some code by opening lib/main.js:

vi lib/main.js

My addon is very simple: copy the URL from current tab, call archive today with this URL in a new tab and finally copy the URL created by archive today to our clipboard.

var buttons = require("sdk/ui/button/action");
var tabs = require("sdk/tabs");
var clipboard = require("sdk/clipboard");

var button = buttons.ActionButton({
    id: "mozilla-link",
    label: "Add to Archive.Today",
    icon: {"16": "./icon-16.png",
          "32": "./icon-32.png",
          "64": "./icon-64.png"},
    onClick: handleClick
});

function handleClick(state) {
    var url = tabs.activeTab.url;
    tabs.open({·
        url: "https://archive.today/?run=1&url="+encodeURIComponent(url),
        onReady: function() {
            clipboard.set(tabs.activeTab.url);
        }
    }); 
}

I added the three icons references in the code to the data directory. To try my new addon out I call cfx run:

cfx run

This opens up a new browser with my addon in it.

Package

TO package my addon and create a XPI-file I simply call cfx again:

cfx xpi

Now I have a add-to-archive-today.xpi that I can install in my browser.