Trickmaker | Solution to hidden treasure of technology
Register or
Login with Facebook for commenting
RSS Trickmaker Home Page Print the Page Mobile Version Trickmaker Desktop Version Trickmaker
advertisement

Be a Guest Blogger

Wednesday, February 23, 2011

Creating your own Firefox add-on using the new SDK

By
Pin It
advertisement
Share It
-----------------------








Firefox 4 promises to be even easier for Add-On developers to dive into, thanks to the new Firefox Add-On SDK. In this article you will take your first steps in developing a simple addon to post to Twitter



Firefox is an incredibly extensible application, not only because there are a large number of add-ons available for the browser, but also because the add-ons for Firefox can make much deeper and more extensible changes to it.
Its extensibility emerges from the way the browser is built. Firefox’s GUI is not coded in C/++, but is instead written in an XML dialect called KUL (XML User Interface Language). A large part of Firefox’s functionality is written in JavaScript, and the browser is styled using and extended from of CSS.
This XUL + CSS + JavaScript code runs on a framework called XUL Runner that renders the XUL code just as a browser would run HTML code. The browser is then running on the same JavaScript engine which web applications will be running on. At its very core XUL Runner is a collection of cross-platform components that includes an XUL and HTML renderer, a networking library, a SQLite database etc. These components can be used by the application running on XUL Runner to provide functionality. In fact Firefox, Thunderbird, and Songbird, three very different applications, all run on Firefox!
Applications that extend Firefox or any XUL Runner-based application overlay their XUL code over that of the application, and are thus able to modify any part of the application’s UI and functionality.
Unfortunately, developing add-ons or applications is not as simple as it might seem. XUL Runner unlike other runtimes such as Adobe AIR, and Titanium was not designed to build applications on, and is this not that well documented. There are few IDEs for developing XUL Runner application. To make matters worse, changes made to Firefox in between versions can stop add-ons written for an older version from working in a newer version.
Now let’s move on to how you can use the Add-On SDK to build extensions for Firefox 4.0 today. We will be creating an extension that will modify the Firefox context menu by adding and option to tweet the text you have selected. This won’t use the proper API for Twitter since that will involve authentication which will be out of the scope of this article. Instead we will use a simpler system that will open Twitter with the text to tweet entered in the tweet box.

Getting started with the Add-On SDK


The first step of course is to get Add-On SDK itself and extract it to a convenient place (the SDK works on Windows Linux and Mac OSX). You will also need Python installed to use the SDK. Install it now.
Since the Add-On SDK is made up of command line tools, you should launch the terminal in your OS. Now you will need to move to the directory in which you have the Add-On SDK installed (“C:\addonsdk” for example) and type “bi\activate” (“source bin/activate” on Linux) to run the activate command which will take you into the Add-On SDK environment.
The command you will be using most of all will be ‘cfx’. The cfx tool will automatically find and use any Firefox instance installed for testing extensions. It might launch Firefox 3.6 if you have that installed along with Firefox 4, so it’s better to specify the particular version of Firefox to use in the command-line. How exactly, we will cover in a bit.
At this point, it helps to run ‘cfx docs’ from the command-line. This will have the Add-On SDK launch a local server for the documentation, and will open the same in a browser.
Create a directory for your add-on (we’ll assume you named it “myaddon”), and enter it in the Add-On SDK environment, then type “cfx init” to initialize the basic structure of the addon in that directory.

The manifest

Before we start with the actual code for the extension, let us first look at the manifest that will contain the metadata (extension name, author name, version, license, description etc).
Inside the folder you created for you addon, you will find a file called ‘package.json’. This is a plain text file that should look something like this:
Here is a sample “package.json” file:
{
“name”: “myaddon”,
“fullName”: “myaddon”,
“description”: “a basic addon”,
“author”: “”,
“license”: “MPL 1.1/GPL 2.0/LGPL 2.1”,
“version”: “0.1”
}
The contents of this file are self explanatory, however do take note of the format, which is something called JSON (JavaScript Object Notation). These are just the basic metadata parameters for the file, there are many others. Not all parameters are necessary, and there is one important parameter “id” that is missing, but will be generated later.
We will now begin with the actual coding for the extension.

The main module

The Add-On SDK is very modular, and uses a popular module standard called CommonJS. Any modules you create for your extension will thus be compatible with other frameworks.
 A file called “main.js” inside the “lib” directory will be where most of your code will lie. It should already have been created by the “cfx init” command you used earlier, and will contain some basic code. You can remove this code to get a clean slate.
Since we wish to modify the context menu for Firefox, we need to import the Jatpack Core module that offers that functionality. Add the following line to your ‘main.js ‘file:
Var contextMenu=require (“context-menu”);
This will let us use the context menu feature defined in the “context-menu” module by referencing them through the contextMenu variable.
We will also be using the tabs API, so include that with:
Var tabs=require(“tabs”);
Now let us create a context menu item. The following is the complete code that we will explain a little later:
Var postTwitter=contextMenu.
Item({
Label: “Tweet”,
Context: contextMenu.SelectionContext(),
ContentScript: ‘on(“click”,
Function (node, data) {‘+’
Var selection=document.getSelection().toString();’+’
postMessage (selection);’+’});’,
onMessage: function(selected Text) {
}
});
We are creating a new context menu item with a label of Tweet”, and three other parameters called context, contentScript, OnMessage which will explain next.

How the code works

context menu, quite obviously, is context-sensitive. What this means is, that the options which appear on the context menu will vary depending on the item you right-click on. We need to specify a context for our menu item to appear in, and Firefox will automatically manage which item to display and when.
This context can be specified in multiple ways:
·         contextMenu.
SelectorContext(selector): The context menu will be displayed on all elements that match the specified CSS selector.
·         contextMenu. SelectionContext(): The context menu will be displayed if there is a selection.
·         contextMenu.
URLContext(match pattern): The context menu will be displayed if the URL of the page matches the specified pattern
·         contextMenu.PageContext(): Displayed everywhere on the page.
You can even specify an array of contexts, in which case the menu will be displayed if all context match. You can even have a custom context, where you code the function that can perform any number of checks before displaying the item in the menu.
An explanation of what is going on here is in order.
 The contentScript is the part of the code that is handled by the context menu. This code is kept separate from the main code of the add-on and is specified in a string although you could load it from a file.
The reason for keeping the code that is executed by the context menu separate from the rest of the add-on code is to make it simpler in the future to move to a model where the add-on, the browser UI, and the content are all running in different processes. This is similar to how Google Chrome works, where each tab is a different process, each add-on is a different process and the browser itself has its own process. Firefox too will embrace this model and when it does add-ons that are developed using the Add-On SDK will continue working.
Since the code running in the context menu is separate from the rest, it cannot directly access variables from the main add-on so how do we tell our add-on that it has been clicked and see a reaction? We use the postMessage function that can be used to send strings and objects (with some restrictions) from the context menu to the add-on. In our case, we are posting the text selected in the document using document.
getSelection().toString()
On the other end, our add-on eagerly awaits a message from the context menu with the receives the message we sent from the context menu and can use it to perform any action.
When it receives the message, in this case it opens a new tab with the URL:
The encode URIComponent function converts our selection to a form that can be safely passed from a URL. This status text is then appended to the URL “http://twitter.com/?status=” that can be use to specify a tweet message while opening the Twitter home page.
You will need to be already logged into Twitter for this. If you are logged in this will open the Twitter home page with the selected text already entered in the tweet box so you can go ahead and click the “Tweet” button to post it.
You can now run “cfx run” from the command line to launch this extension in your browser. When you run the “cfx run” command for the first time, it will simply modify your ‘package.json’ file to include a unique id; you will have to run it a second time to launch it in your browser.
Note that by default the “cfx” command might launch the wrong version of Firefox (Firefox 3.6) which will fail to enable this extension. In this case you should specify which Firefox version to use by providing its path in the commandline:
Cfx run –b C:\path\to\firefox4\firefox.exe
OR crx run –binary=C:\path\to\firefox4\firefox.exe
You can see how simple developing extensions for Firefox is about to become! With just a few lines of code we have a functional extension of some utility. Currently the Add-On SDK is not even complete, it is all extensions using this SDK will get features such as restart-less installation, future compatibility and a consistency in appearance and function without any extra effort.









Attachments:


If you LIKE this, then copy the below and put this in your WEBSITE or BLOG