Developing a Firefox Extension – the complete tutorial!

by Veera on December 7, 2009

in How To, Tools, Web

I hope that you have got a basic idea about the Firefox extension development from my previous posts. In this post, lets actually start developing a simple Firefox extension.

What are we going to build?

We are going to build a extension for helping the people who are doing the day trading in NSE of Indian Stock Market. The user can use our extension to monitor her profit/loss on a given day, after configuring the stock details that she bought. We will be using ICICIDirect.com for getting the stock prices. Lets name this extension as Stockr (sounds web2, isn’t it? :D ).

Important: The Firefox extension that we are going to build in this post is already uploaded to Firefox’s gallery – Stockr extension. By downloading the extension, you get to run it and you get the source code too. So, I recommend to download the extension and extract it to get the source code, which will help you in understanding this tutorial better.

Summary of steps to build a Firefox extension

  1. Create a new Firefox profile (optional, but recommended).
  2. Create the folder structure for the Firefox extension.
  3. Decide on the extension name and edit the install.rdf with the extension descriotion and author information.
  4. Create your extension user interface as a XUL file, with depended JavaScripts, if any and put them under the chrome/content/ folder.
  5. Link your extension with the Firefox UI by editing the chrome.manifest file.
  6. Test your extension and edit if necessary (recursive step).
  7. Bundle your extension and distribute.

1. Create a Firefox profile

By creating a new Firefox profile, we are making sure that the default Firefox profile is not affected due to our development activities. At any time we can switch back to the default profile, if we want to use Firefox for just browsing. Off course, you can continue the extension development with out creating a new Firefox profile. It will do no harm. But it is recommended to have a development profile. You can check my last article to know more about Firefox profiles and how to create a new one.

2. Firefox extension – Folder Structure

If you are familiar with Java web applications, you must be knowing that each application follows a certain folder structure. Similar to that, there is a folder structure for the Firefox extension also which tells about how things are organized and what are all the mandatory files to be present in an extension. You can create these files anywhere in your system (C:\dev\ff\stockr, for example). For our Stockr extension, the folder structure looks like:

stockr\
        install.rdf
        chrome.manifest
        chrome\
                  content\

3. Edit install.rdf for extension description and installation info

This is an important step. By editing install.rdf file, you are telling the Firefox about the name of your extension, a description, upto what Firefox versions your extension is compatible, who developed it, etc, etc. If there are any errors in this file, then there are chances that your extension will not be properly installed. Now open your install.rdf file, and copy the below lines into it.

<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
     xmlns:em="http://www.mozilla.org/2004/em-rdf#">

  <Description about="urn:mozilla:install-manifest">
    <em:id>stockr@veerasundar.com</em:id>
    <em:version>1.0</em:version>
    <em:type>2</em:type>

    <!-- Target Application this extension can install into,
         with minimum and maximum supported versions. -->
    <em:targetApplication>
      <Description>
        <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
        <em:minVersion>1.5</em:minVersion>
        <em:maxVersion>3.5.*</em:maxVersion>
      </Description>
    </em:targetApplication>

    <!-- Front End MetaData -->
    <em:name>Stockr</em:name>
    <em:description>NSE (India) Stock price tracking extension.</em:description>
    <em:creator>Veerasundar</em:creator>
    <em:homepageURL>http://www.veerasundar.com</em:homepageURL>
  </Description>
</RDF>
Important: For your extension, be sure to change the value stockr@veerasundar.com to a different one. This is the unique id for each Firefox extension and it should be in the form of an email address (need not to be a real address). And you can edit the other information like extension description, etc. I hope no explanation is needed there.

Another notable setting here is the <em:maxVersion> which tells the maxium version of Firefox compatible with your extension. I’ve set it as 3.5.* so, my extension is compatible with Firefox 3.5.1, 3.5.2, …

4. Create the extension UI using XUL

Now create a new file stockr-ui.xul isnide the directory stockr/chrome/content/ and copy the below lines into it.

<?xml version="1.0"?>
<overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" >

	<script type="text/javascript" src="stockr-script.js"></script>
	<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

	<statusbar id="status-bar">
		<statusbarpanel id="stockr-panel" context="stockr-ctx-menu">
			<label id="stockr-display" tooltiptext="Right click and Add stock to start monitoring">Stockr</label>
			<image id="status-image" src="chrome://stockr/content/none.png"/>
		</statusbarpanel>

		<menupopup id="stockr-ctx-menu">
			<menuitem label="About Stockr" oncommand="stockr.about()"/>
			<menuseparator/>
			<menuitem label="Refresh" oncommand="stockr.refresh()"/>
			<menuitem label="Clear Stock" oncommand="stockr.clear()"/>
			<menuitem label="Add Stock" oncommand="stockr.addStockCode()"/>
		</menupopup>
	</statusbar>

</overlay>

As you can see in the code above, we are creating a overlay element. You can place the overlay element over the top of Firefox UI. Then inside, we are defining a statusbar element with the id = “status-bar”. This is the ID of Firefox’s statusbar. So our extension UI will be attached to the standard statusbar.

You can modify these elements in a similar way you modify any other HTML elements using JavaScript. For example, we have defined a <label> element with an ID stockr-display. So, from my JavaScript, I would be getting this element as document.getElementByID and then I’ll be modifying the content the usual way as how I do it for a HTML element. To make things clear, lets look at the JavaScript code, too. Blow are the contents of the stockr/chrome/content/stockr-script.js, which we had already included in our stockr-ui.xul file.

var DO_STOCK_TRACKING = true;
var tickerTimer;

function Transaction(stockCode, boughtPrice, numOfShares){

	// attributes
	this.stockCode = stockCode;
	this.boughtPrice = boughtPrice;
	this.numOfShares = numOfShares;

	// methods

	// fetch the latest price of this stock from ICICI site and returns it.
	this.getStockCurrentPrice = function(){

	},

	// return the profit/loss position as a formatted string
	this.refreshTransactionPosition = function(){

		if(!DO_STOCK_TRACKING){
			return;
		}

		var SRC_URL = "http://getquote.icicidirect.com/trading/equity/trading_stock_quote.asp?Symbol=";
		var queryString = SRC_URL + this.stockCode;

		var panel = document.getElementById('stockr-display');
		var statusImage = document.getElementById('status-image');
		statusImage.src = "chrome://stockr/content/ajax-loader.gif";

		$.get(queryString, function(data){

			var filteredData = data.substr(data.indexOf("PRICE"), 120);
			var currentPrice = parseFloat(filteredData.match(/[\d\.\d]+/));

			var priceDiff = (currentPrice - boughtPrice)*numOfShares;

			// now round the price difference
			priceDiff = Math.round(priceDiff * 100)/100;

			var position = "";
			if(priceDiff < 0){
				position = stockCode + " : " + priceDiff;
				statusImage.src = "chrome://stockr/content/down.png";

			}else{
				position =  stockCode + " : " + priceDiff;
				statusImage.src = "chrome://stockr/content/up.png";
			}
			panel.value = position;

			// set the timeout for next data refresh
			tickerTimer = setTimeout("stockr.refresh()", 10*1000);
		});

	}
}

// the stock variable
var tx;

var stockr = function(){
	return{
		init: function(){
			var panel = document.getElementById('stockr-display');
			panel.value = 'Stockr';
			panel.tooltiptext = "Right click and add stock to start monitoring";
		},

		addStockCode: function(){

			var stockCode = prompt("Enter the stock code: (from ICICIDirect.com) ");
			stockCode = stockCode.toUpperCase();
			var stockPrice = prompt("At what price did you buy " + stockCode + " ?");
			var numOfStocks = prompt ("How many " + stockCode + " did you buy?");

			tx = new Transaction(stockCode, stockPrice, numOfStocks);
			DO_STOCK_TRACKING = true;
			this.refresh();
		},

		clear: function(){

			DO_STOCK_TRACKING = false;
			clearTimeout(tickerTimer);

			var panel = document.getElementById('stockr-display');
			var statusImage = document.getElementById('status-image');
			statusImage.src = "chrome://stockr/content/none.gif";
			panel.value = 'Stockr - NSE Stock Tracker';

		},

		refresh: function(){
			tx.refreshTransactionPosition();
		}

	};
}();

window.addEventListener("load", stockr.init, false);

A lot of code, isn’t it? Anyway, I’m not going to explain it line by line, since mostly it is the business logic. Just go through the function refreshTransactionPosition() as it contains core logic of fecthing new stock values and updating it on the UI. If you have any doubts/questions, ask it in the comments. I’ll try to clarify.

Important: My JavaScript code make use of the JQuery library. So, in order to run this script, you may need to place the JQuery libary under the folder stockr/chrome/content/.

5. Linking our extension with Firefox UI

Now we are so close to complete. In this step, we will link our extension UI with the Firefox UI so that when Firefox loads, it will also show our extension over the status-bar (remember stockr-ui.xul, where we attached our panel to status-bar?). Now open the chrome.manifest and copy the below lines into it.

content stockr chrome/content/
overlay chrome://browser/content/browser.xul chrome://stockr/content/stockr-ui.xul

Whoa! Finally, a file with just two lines in it!! :) Okay, Jokes apart.What we are doing in this file is we are informing the Firefox to draw our extension UI over the browser UI. In our stockr-ui.xul, we have attached the extension to the status-bar. So, when Firefox loads, our extension UI will be sitting quitely on the Firefox’s status-bar.

6. Testing our extension

The next step is to, obviously, testing our extension. We need to tell Firefox to load/install our extension. To do that, follow these steps:

  1. In Windows, navigate to your Firefox’s profile directory. In its a default profile, then usually it is : C:\Documents and Settings\user_name\Application Data\Mozilla\Firefox\Profiles\e7rhpqb4.default\
  2. Now open the extensions folder (create one, if there is none!).
  3. Create a text file in the name of your extension unique id (which we gave it while editing install.rdf file). So, for our extension, it will be stockr@veerasundar.com.
  4. Now enter the full path of your extension location. i.e. C:\dev\ff\stockr inside the file and save it. This acts like a shortcut for the Firefox to navigate to this folder and load the extension.

After done the above, re-start the Firefox and Bingo! There is our first extension running successfully (if you did every thing right!).

7. Bundle and Distribute

The FINAL step. Bundle your extension files, which is under C:\dev\ff\stockr\and save it as a zip file – stockr.zip. This is our final deleivarable. You can distribute this to any person who is using Firefox. You can even upload it to Firefox’s extension gallery, to share it with the world!

Important: The Stockr extension is already uploaded to Firefox’s galley and available for download.

So, with that we come to the end of this tutorial. I hope that you liked it, as I did. Do share your thoughts and questions (if any). I’ll try to clarify it.

Follow me on Twitter to get notified whenever I update this blog.

{ 4 comments }

tahirakram December 20, 2009 at 3:38 PM

A great resource. I will surely use it when I got any idea about Firefox extension development.

Veera December 20, 2009 at 4:10 PM

thanks, Tahir!

angelinvestors December 23, 2009 at 7:46 AM

Stockr woh its going to super use for investors in stock .
As they can moniter up and downs.
I would see more like tips for the stock.

Thanks Veer looking for more innovations…..

Veera December 23, 2009 at 10:28 AM

thank you for your comment. :)

//I would see more like tips for the stock.//

Well, I dont trade/invest in a big scale in stock markets. So, I may not be the best person to give advice on that aspect. anyway, you can look at this website : http://nseguide.com – which looks promising on stock advices.

Comments on this entry are closed.

Previous post:

Next post: