Docstoc

How to Create a new Firefox Extension and Installation

Document Sample
How to Create a new Firefox Extension and Installation Powered By Docstoc
					Firefox Extension Development Tutorial :: Overview
Table of contents
1 2 3 4

Development Overview..................................................................................................... 2 Extension Overview...........................................................................................................2 Useful Tools.......................................................................................................................4 Further Reading..................................................................................................................5

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Overview

1. Development Overview
This tutorial has been created for individuals wanting to develop full-featured extensions for the Mozilla Firefox browser. The tutorial has been constructed as a step-by-step guide providing many examples, explanations, and external references to help the reader have a full understanding of extension development. Please use the menu on the left to navigate through this tutorial. Each section has been dedicated to a certain stage of the development process. It is recommended that you read through the tutorial in order, as some information builds upon previous sections. The following major topics are covered in this tutorial: • Packaging and Distributing Extensions • Creating and Modifying User Interfaces • Firefox Integration (API basics) • Creating User Preferences to store information • Creating User Preferences Pane (for the Options window)

2. Extension Overview
The authors of this tutorial were in your shoes just a few weeks ago: knowing absolutely nothing about developing Firefox extensions. Through hours of research, however, we have developed our own extension that will be used throughout this tutorial to provide you with examples. The demonstration extension is named 'Home Page Scheduler' and provides the user with the ability to easily schedule specific websites to be their Home Page depending on the current time and day. For example, you may prefer for your home page to be weather.com between 8am-10am, cnn.com between 10am-2pm, slashdot.org between 2pm-5pm, and google.com in the evening. The extension has been developed with many features so that we are able to use it as a full example in this tutorial (some of these features are not necessary for this specific extension, but that is ok). Please click here to install the Home Page Scheduler Extension. Or, for the source, click here for the zip file containing the extension files. This screenshot of the Home Page Scheduler extension shows the preferences window that allows users to schedule new home pages.

Page 2

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Overview

Preference Windows This second screenshot shows the preference screen when the user is creating a new schedule.

Page 3

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Overview

New Schedule Window

3. Useful Tools
Now is a good time to introduce you to some built-in tools that may help you in the near future. The first one is viewing the user preferences currently being used in the Firefox instance. To do this, simply type 'about:config' in the location bar of Firefox. You will see a listing of all the preferences currently stored, along with their values. Double click these items to modify the value. Another useful tool is the DOM Inspector. This can be found in the Tools menu of your Firefox installation. Spending a few minutes familiarizing yourself with this utility may save
Page 4

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Overview

you some time in the future!

4. Further Reading
about:config: http://kb.mozillazine.org/Firefox_:_FAQs_:_About:config_Entries DOM Inspector: http://www.mozilla.org/projects/inspector/

Page 5

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Environment
Table of contents
1 2 3 4

Environment Overview...................................................................................................... 2 Getting Firefox 1.5.............................................................................................................2 Zip Utility...........................................................................................................................2 File Extensions...................................................................................................................2

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Environment

1. Environment Overview
It will be beneficial to setup your computer for the development process before you dive in. This section will help you do just that. Fortunately for developers and users alike, extensions written for Firefox are platform independent. This means that you may code your extension on whichever operating system you are most comfortable with (Windows, Mac OS X, Linux).

2. Getting Firefox 1.5
The Mozilla Foundation has made many improvements to the extension framework used by Firefox. These changes have been incorporated into the next major release, version 1.5. As of early November 2005, this version is in the Release Candidate stage. The official version should be released within the next several months. This website describes how to develop extensions for Firefox 1.5, and thus you will need to upgrade your browser. During the install process, select the 'Custom' Setup type and ensure that the 'Developer Tools' components are being installed. Please click here to download Firefox 1.5 RC1.

3. Zip Utility
You will soon learn that a Firefox Extension is nothing more than a file hierarchy that has been compressed into a zip file. In order to package your extension, you will need to be able to zip up files on your computer. • Mac OS X: If you installed the Developer Tools when installing this operating system you already have the zip utility installed. Open up your Terminal and type zip. If you receive a 'File Not Found' error, you may download an install package for the zip utilities from here. • Windows: If you are running Windows XP you should be able to right click on a file, choose 'Send To...' and then 'Compressed (Zipped) Folder'. If you do not have this option you will need to download a compression utility. We recommend WinZip! • Unix: If your Unix system does not have zip installed, please follow your distribution's documentation to determine how to install the binary (it is very common).

4. File Extensions
The Windows operating system, by default, hides the file extension of known file types (such as .doc, .zip, .ppt, etc.). At many points during extension development it will be much easier

Page 2

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Environment

if you are able to view and edit the full file name. Choosing not to perform this step could cause you some confusion in the future. Forcing Windows to show the full filename is not difficult, please follow these steps: 1. Open a folder window (such as My Computer). 2. Select Folder Options from the Tools menu. 3. Select the View tab. 4. Ensure that the Hide extensions for known file types item is not checked. 5. Press the OK button.

Page 3

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Configuration Files
Table of contents
1 2 3 4 5

Overview............................................................................................................................2 Install Manifest.................................................................................................................. 2 Chrome...............................................................................................................................4 Chrome Manifest................................................................................................................4 Further Reading..................................................................................................................5

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Configuration Files

1. Overview
A Firefox Extension is a collection of files and folders that have been compressed into a file with a .xpi extension. The .xpi file (pronounced zippy) is nothing more than a .zip file that has been renamed. Create a folder (wherever you feel most comfortable, such as the Desktop) named 'MyExt'. Truthfully, the name of this folder is up to you, but I will refer to it as 'MyExt' throughout this tutorial. Within this folder you will need to create the following directories:
MyExt/ chrome/ chrome/chromeFiles/ chrome/chromeFiles/content/ defaults/ defaults/preferences/

These directories will remain empty for now. There are two text files that you will need to create at the root of the MyExt folder. These files are configuration files that provide information to the Firefox extension framework. Each of these are described below. Alternatively, you may download a MyExt.zip file that already contains the empty directories.

2. Install Manifest
An Install Manifest is the file used to provide information about a Firefox addon (extension, plugin, component, ..) while it is being installed. The file contains metadata identifying the addon, providing information about who created it, where more information can be found about it, which applications and versions it is compatible with, and more. To create your Install Manifest, create a text file called 'install.rdf' and place it in the root of your MyExt directory (i.e. MyExt/install.rdf). Paste the following information into this file:
<?xml version="1.0"?> <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>sample@sample.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. -->

Page 2

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Configuration Files

<em:targetApplication> <Description> <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <em:minVersion>1.5</em:minVersion> <em:maxVersion>1.5</em:maxVersion> </Description> </em:targetApplication> <!-- Front End MetaData --> <em:name>My Extension</em:name> <em:description>A sample extension.</em:description> <em:creator>Your Name Here</em:creator> <em:homepageURL>http://www.mypage.com/</em:homepageURL> </Description> </RDF>

At this time you should modify this generic information to match your needs. Here is a breakdown of the first section: 1. id: This is this value which uniquely identifies your extension. This ID should simply be your email address. This ensures that the ID will be different than those of other extensions. It is possible to use a GUID as well, but this is no longer necessary or recommended. 2. version: This string identifies the version of the extension being installed. The version number is completely up to you, however it is recommended that you use versions less than 1.0 when in development stages. When you feel confident your extension works well, you may make the version be 1.0. Future improvements should increase the version number as appropriate. For Firefox 1.5, a version string consists of one or more version sections, separated with dots. Each version section is a sequence of four parts : <number-a><string-b><number-c><string-d>, where each of the parts is optional. Numbers are integers base 10, and strings are ASCII. Example: 1b2a. 3. type: This integer value represents the type of addon being installed. For an extension, this number should always be 2. The targetApplication section defines which application is targeted by this extension. The <em:id> field defines which application your addon is created for, and is currently set to Firefox in the sample file. This tutorial only provides Firefox details, so this GUID should remain constant. The <em:minVersion> and <em:maxVersion> fields simply tell Firefox which versions of Firefox the extension is designed for. These values will be compared to the value of the app.extensions.version preference and can be different from the actual version of Firefox (yes, it is annoying). For example, Firefox versions 1.0 - 1.0.6 all have app.extensions.version of 1.0. The last section of data describes your extension: 1. name: This line simply defines the name of your extension and is intended for display in the UI of Firefox.

Page 3

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Configuration Files

2. description: This line should describe the functionality of your extension and is intended to be displayed in the UI. It should fit on one line in order to display properly in the user interface. 3. creator: This line should contain your name and will be used to display your name in the UI. 4. homepageURL: This line is optional and is simply just a link to the author's homepage. If you have a personal homepage that you would like to reference, put it here.

3. Chrome
Before we talk about the Chrome Manifest file we must learn what 'chrome' means. Chrome is the term used to refer to Interface Packages created for Firefox. The Firefox browser contains a component, the Chrome Manager, that handles the installation and loading of the various parts of Firefox. Everything from the guts (global, browser, etc.) to extensions (such as yours!) register themselves with this manager. Chrome uses URIs just like you are used to on the web (http). However, in order for Firefox to know it is working with a chrome package, the 'chrome' prefix is used (instead of http). For example, there is a built-in package called 'browser'. This package can be referenced as 'chrome://browser'. Let's look at the browser package a little more. This Chrome package, much like your extension will, provides User Interface and backend code for Firefox. We can inspect the browser package's primary User Interface file: browser.xul. Open up your DOM Inspector and type 'chrome://browser/content/browser.xul' into the location bar. Now press the inspect button (enter will not work). From the View menu make sure that 'Browser' is checked. You can see here what looks exactly like your browser! That is because you have loaded the layout file (inside the Browser Chrome package) and are currently inspecting it.

4. Chrome Manifest
As we proceed through the tutorial you will add many lines to the chrome.manifest file located at the root of the MyExt directory. For now, we will add one line that tells Firefox where to find the content needed to display and execute your extension:
content sample chrome/chromeFiles/content/

This line says that for the chrome package named 'sample', Firefox can find the content files at the location chrome/chromeFiles/content which is a path relative to the location of chrome.manifest (you created this directory above). At this time you should come up with a unique package name for your extension (instead of

Page 4

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Configuration Files

'sample'). For the Home Page Scheduler extension we used 'hpsched'. In the next few steps we will create the actual content that Firefox will be looking for.

5. Further Reading
Install Manifest Details: http://developer.mozilla.org/en/docs/Install_Manifests Chrome Manifest Details: http://developer.mozilla.org/en/docs/Chrome_Manifest All About Chrome: http://www.mozilla.org/xpfe/ConfigChromeSpec.html

Page 5

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: GUIs
Table of contents
1 2 3 4

Overview............................................................................................................................2 Common Elements.............................................................................................................2 XUL Overlays.................................................................................................................... 3 Further Reading..................................................................................................................4

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: GUIs

1. Overview
Most Firefox extensions have one goal in common: wanting to add or change some graphical element(s) in Firefox. Fortunately for us, adding and modifying GUIs (Graphical User Interfaces) is quite easy thanks to the decision to create an interfacing language specifically for Firefox, from the ground up. This language is called XUL (XML User Interface Language, pronounced zool) and is not too difficult to learn, as it follows the normal XML syntax. Graphical elements, such as buttons, lists, menus, and windows, are all XUL elements that have been placed into an XUL file and loaded by the browser. XUL files are always found within the content section of a Chrome package. Remember the last step when we added the content line to the chrome.manifest? That told Firefox that the XUL files for that package, sample, could be found in that content directory. Thus, when making GUIs just put the .xul files in your content directory, along with any JavaScript files that will be needed.

2. Common Elements
Let's look at some very common elements used in XUL. First, the button:
<button label="Create New Schedule" id="createSchedule" oncommand="newSched();">

It is that simple! Just give the button a label (for the GUI), an ID (so we can reference this element from the JavaScript), and a command to perform when pressed (in this case, we call a function). Create a simple label to be placed on the window:
<label value="Location(s)" />

Use a groupbox to separate items into subsections. The General tab in the Options window uses this, for example.
<groupbox id="schedulesListGroupBox"> </groupbox>

You can also use <hbox> and <vbox> to lay out elements horizontally or vertically, respectively.
<hbox>

Page 2

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: GUIs

...these elements will be on the same row... </hbox> <vbox> ...these elements will be above/below each other... </vbox>

The following resource is wonderful at describing the different XUL elements you can use. Spend some time looking through the list so you will know what XUL has to offer. http://xulplanet.com/references/elemref/

3. XUL Overlays
In addition to being able to create new elements on your own windows (see the Preferences section), you can also modify parts of the GUI that are already present. For example, let's say we want to add a menu option to the Tools menu. This is quite simple:
<menupopup id="menu_ToolsPopup"> <menuitem label="HP Scheduler Options..." insertafter="devToolsSeparator" oncommand="openPreferences('hpschedPane');" /> </menupopup>

Menu Screenshot You can see that a new menuitem has been created and given a label, where to insert the item in the menu, and a command to run when clicked. But how does our code know to insert the menu item into the already created Tools menu? This is where XUL Overlays come into play. Your XUL file can be overlaid onto another (built-in) XUL file and Firefox will automatically merge the two files. The XUL for menus can be found in chrome://browser/content/browser.xul. Thus, we need to overlay our xul file, say browser_overlay.xul onto the browser.xul file. We will do this by adding a line to our chrome.manifest file.
overlay chrome://browser/content/browser.xul chrome://hpsched/content/browser_overlay.xul

This line tells Firefox to merge the data in the browser_overlay.xul anytime the browser.xul file is loaded. Notice the first line in the code, above:
<menupopup id="menu_ToolsPopup"> ... </menupopup>

If you look in chrome://browser/content/browser.xul you will see that there exists a

Page 3

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: GUIs

menupopup tag with the same ID that we used. This means that any children (the ...) that we include within this child will be added to the browser file. This is called a merge point. As another example we could add an icon to the status bar panel. First we determine what the merge point is using the DOM Inspector and find that its ID is 'status-bar'. Now we can include this in our overlay file and anything inside it will be inserted at this location in the actual browser.xul file.
<statusbar id="status-bar"> <statusbarpanel class="statusbarpanel-iconic" id="hpsched_sbi" onclick="openPreferences('hpschedPane');" src="chrome://hpsched/content/images/hpsched18.png" /> </statusbar>

Statusbar As the image shows, two icons have been added to the statusbar area. One is ours and one belongs to another extension that did the same thing (ReminderFox). If you would like to remove an element that is already in the browser.xul file just add the removeelement attribute. For example, we could completely remove the Tools menu!
<menupopup id="menu_ToolsPopup" removeelement="true">

4. Further Reading
XUL Planet: http://xulplanet.com XUL Element Reference: http://xulplanet.com/references/elemref/

Page 4

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial
Table of contents
1 2 3 4

Overview............................................................................................................................2 JavaScript Basics................................................................................................................2 Working with the DOM..................................................................................................... 3 Further Reading..................................................................................................................4

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial

1. Overview
All of the guts of your extension will be written in JavaScript. If you already know JavaScript than you are good to go! If you are new to JavaScript it is highly recommended that you read through the next section and the supporting documentation to get used to the syntax. All of your JavaScript code files should go in the content directory of your extension. This is where the XUL files go as well, so they will be able to easily reference the code. Just insert the following line in an XUL file that needs to run functions from your files...
<script type="application/x-javascript" src="chrome://hpsched/content/mycode.js" />

Make sure you use the chrome URI so that Firefox can find the file correctly.

2. JavaScript Basics
JavaScript is a fairly straight forward scripting language. Let's jump right into some sample code:
/* * Save the Schedules List to the "extensions.hpsched.schedules" preference. * This is called by the pref's system when the GUI element is altered. */ function saveSchedulesList() { var schedulesList = document.getElementById("schedulesList").childNodes; var prefString = ""; for (var i=0; i < schedulesList.length; i++) { var columns = schedulesList[i].childNodes[0].childNodes; var str = columns[0].getAttribute("label") + ".ITEM." + columns[1].getAttribute("label") + ".ITEM." + columns[2].getAttribute("label") + ".ITEM." + columns[3].getAttribute("label"); if(prefString == "") prefString = str; else prefString += ".NEXT." + str; } /* return the new prefString to be stored by pref system */ return prefString; }

Page 2

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial

The first line defines a function named 'saveSchedulesList' that brings in zero arguments. The next two lines create and initialize two variables. Notice that JavaScript is a typeless language, just type var to let the parser know you are declaring a variable. The for-loop and if statement looks just like what you would expect in C or Java. You will also notice that you do not have to state that this function is (or is not) returning a value. If you would like to return a value, just use the common 'return x;' statement. If no return statement is provided than the function returns (void), which is ignored by the calling function. Debugging JavaScript is also quite easy: just use the 'alert()' function call. Whenever Firefox is running code and sees a call such as 'alert("I am here!");', Firefox will display a graphical error box with the given message. This is a wonderful way to determine if a certain area of code is being executed, what the current value of some variable is (i.e. alert(myVar)), and more. Use alert(), it is your friend! Please see the Further Reading section for links to some wonderful JavaScript tutorials.

3. Working with the DOM
JavaScript is very common in web development because it provides functionality to easily work with the DOM (Document Object Module). All HTML files on the net are rendered by the browser by first building a tree. Each node in the tree corresponds to a tag in the HTML file. Firefox's XUL files work the same way, all elements are nodes in a large tree (per file). The top level element is called the 'document'. There is one very important JavaScript function that you will need to know to be able to work with the XUL elements in your GUI. It allows you to access the object itself, using its ID. For example, when the Home Page Scheduler wants to load the saved schedules into the tree element that displays them to the user, it need to get access to the tree object itself. The tree's ID is schedulesTree.
<var schedulesTree = document.getElementById("schedulesTree");

This returns the object representing the tree element. At this point we can get and set various attributes related to the tree object. For example, to get the currently selected index we just use 'schedulesTree.currentIndex'. To see a list of attributes and methods defined for the various element types just look them up in the XUL element reference mentioned earlier: http://xulplanet.com/references/elemref/. You can learn all about the tree element, for example, here: http://xulplanet.com/references/elemref/ref_tree.html.

Page 3

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial

4. Further Reading
XUL Element Reference: http://xulplanet.com/references/elemref/ref_tree.html JavaScript Tutorials and Reference: http://www.w3schools.com/js/default.asp A great JavaScript Tutorial for the Total Non-Programmer: http://www.webteacher.com/javascript/

Page 4

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Preferences
Table of contents
1 2 3 4 5 6 7

Overview............................................................................................................................2 Setting Defaults..................................................................................................................2 Referencing from JavaScript..............................................................................................2 Creating a Preferences Pane...............................................................................................3 Making XUL Elements bind to Preferences...................................................................... 4 More Difficult Preferences interfaces................................................................................ 5 Further Reading..................................................................................................................7

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Preferences

1. Overview
In many cases your extension will need to be able to store data or simple user preferences for future use. In the Home Page Scheduler, for example, the Default Home Page URL and the scheduled Home Pages all need to be saved somewhere so that each time the user opens Firefox the data is available. Firefox provides you with the Preferences System for these tasks. To see all of the currently stored preferences in your Firefox, type 'about:config' into the location bar and press return. This page will show you a listing of all the current preferences and their values. For example, browser.startup.homepage tells the browser what page to load when the user wishes to visit their home page. A preference can be an int, bool, or string.

2. Setting Defaults
The preference strings that you create for your extension should follow a simple naming convention. Here is the preference that holds the Default Home Page for our extension: extensions.hpsched.defaultHomePage Begin your strings with 'extensions', followed by your package name, and then the rest can be whatever makes the most sense to you. This just makes sure no two extensions want to create the same preference string for two different reasons. In most cases you will want to set what should be the default setting for a preference. For example, in the Home Page Scheduler www.google.com is the default startupHomePage if the user does not provide one. You may create these default preferences in a file within your defaults/preferences directory (you created this directory earlier). All .js files within this directory will be loaded by the Preference System when necessary, so the name of your file does not matter. We chose to use our package name: hpsched.js. Within this file you may add lines like this: pref("extensions.hpsched.defaultHomePage", "www.google.com"); pref("extensions.hpsched.schedules", ""); Notice that, by default, no scheduled events are created, so we just initialized this to an empty string.

3. Referencing from JavaScript
The steps necessary to reference the preferences system from within the JavaScript code could have been made simpler, but it is not too bad. First, your file must have access to the Preference Manager component. To do that, you must add the following line of code to your file:
Page 2

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Preferences

var prefManager = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefBranch);

Now that you have access to the preference manager you can get and set preferences using getIntPref()/getBoolPref()/getCharPref() and setIntPref()/setBoolPref()/setCharPref(). These functions are very straight forward and have been used in the code samples above.

4. Creating a Preferences Pane
Before we begin using our preference strings to store data, let's learn how to create a Preferences pane. Select Options from the Tools menu in Firefox to open up your preferences. (Note: options and preferences means the same thing in Firefox). You should see General, Privacy, Content, Download, Advanced, and maybe other tabs. If you would like to have a tab for your extension preferences, you must create an XUL overlay onto the preferences.xul file that contains your pane information. The code below shows how to create an XUL overlay for your pane:
<?xml version="1.0"?> <overlay id="hpsched_preferences_overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <!-- Merge with the BrowserPreferences Window --> <prefwindow id="BrowserPreferences"> <!-- Create a new pane (tab) for HP Scheduler. --> <prefpane id="hpschedPane" label="&prefpane.label;" onpaneload="populateSchedulesList()" image="chrome://hpsched/content/images/hpsched32.png"> <!-- Intermediary between GUI and preferences system --> <preferences> <!-- see the next section for more information --> </preferences> <!-- GUI Elements... --> </prefpane> </prefwindow> </overlay>

Notice that the merge point is <prefwindow id="BrowserPreferences">. If you did not know what you want to merge with, the DOM Inspector is your best tool for looking through browser code and finding element IDs. The <prefpane> tag requires an id, label, and image attributes. This image will show up in the Options window. The onpaneload attribute allows you to run code when the options pane is first loaded.

Page 3

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Preferences

Here is a screenshot of the Home Page Scheduler Preference Pane. Notice that buttons, textboxes, and all other GUI elements work just fine in the Options window.

Preference Window

5. Making XUL Elements bind to Preferences
There are two steps to making your XUL element interface with a preference string. We will use the Default Home Page textbox as an example. First, within the <preferences> tag shown in the sample above, you will need to define the preference that will be used:

Page 4

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Preferences

<preferences> <preference id="defaultStartupHomepage" name="extensions.hpsched.defaultHomepage" type="string" /> </preferences>

This line creates an element with the defaultStartupHomepage DOM ID, and associates itself with the extensions.hpsched.defaultHomepage preference string. It also lets the preference system know that the data should be stored as a string (not an int or bool). We can now use this element's ID in the XUL GUI element:
<textbox preference="defaultStartupHomepage" id="defaultStartupHomepageField" />

For simple elements, such as checkbox, colorpicker, radiogroup, textbox, listitem, listbox, and menulist, all you have to do is add the preference attribute to the element. The Preference System will automatically update the preference string anytime this element is modified! This was a major Firefox 1.5 improvement.

6. More Difficult Preferences interfaces
In some cases your GUI elements will not have a one-to-one correspondence with the preferences strings. In the Home Page Scheduler, for example, the tree element that holds our scheduled home pages cannot automatically store its data as an int, string, or bool - it is much too complicated. The Firefox Preference Manager provides a way for you to interface with more complicated GUI elements. There are three basic steps: 1. onpaneload: Add this attribute to your prefpane tag so that a function can be called to initialize your GUI elements. At this point in the code you can access the preferences strings manually and set the GUI elements as desired. 2. onsynctopreference="return myFunc();": This attribute must also be inserted into the element that will be altering the preference's value. Anytime the user changes the element, the Preference System will call this function to update the preference string. This function must return the new value of the preference string, which will then be stored immediately. 3. preference-editable="true": You must add this attribute to the XUL elements that should cause the preference string to be modified. That way, the Preference System can call your update code as soon as the user modifies the element. Let's look at the onpaneload code for the Home Page Scheduler. You will see that it manually retrieves the preference and builds the tree's child nodes to match the information:
/*

Page 5

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Preferences

* Called when the preference window loads. Populates the Schedules List * based on the "extensions.hpsched.schedules" preference. */ function populateSchedulesList() { var prefString = prefManager.getCharPref("extensions.hpsched.schedules"); if(prefString == "") return; var schedules = prefString.split(".NEXT."); var schedulesList = document.getElementById("schedulesList"); for (var i=0; i < schedules.length; i++) { var pieces = schedules[i].split(".ITEM."); var newItem = document.createElement("treeitem"); var newRow = document.createElement("treerow"); newItem.appendChild(newRow); var date = document.createElement("treecell"); date.setAttribute("label", pieces[0]); newRow.appendChild(date); var start_time = document.createElement("treecell"); start_time.setAttribute("label", pieces[1]); newRow.appendChild(start_time); var end_time = document.createElement("treecell"); end_time.setAttribute("label", pieces[2]); newRow.appendChild(end_time); var url = document.createElement("treecell"); url.setAttribute("label", pieces[3]); newRow.appendChild(url); schedulesList.appendChild(newItem); } }

Here is our tree element in the XUL file:
<tree id="schedulesTree" preference-editable="true" preference="schedules" onsynctopreference="return saveSchedulesList();">

Last we must provide the function that converts the information from the tree into a string suitable for preference storage:
/* * Save the Schedules List to the

Page 6

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Preferences

"extensions.hpsched.schedules" preference. * This is called by the pref's system when the GUI element is altered. */ function saveSchedulesList() { var schedulesList = document.getElementById("schedulesList").childNodes; var prefString = ""; for (var i=0; i < schedulesList.length; i++) { var columns = schedulesList[i].childNodes[0].childNodes; var str = columns[0].getAttribute("label") + ".ITEM." + columns[1].getAttribute("label") + ".ITEM." + columns[2].getAttribute("label") + ".ITEM." + columns[3].getAttribute("label"); if(prefString == "") prefString = str; else prefString += ".NEXT." + str; } /* return the new prefString to be stored by pref system */ return prefString; }

7. Further Reading
Preferences Overview: http://developer.mozilla.org/en/docs/Preferences_System:preference

Page 7

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Localization
Table of contents
1 2 3 4 5 6

Overview............................................................................................................................2 Entities as String Constants............................................................................................... 2 Language Document Template Definition (DTD).............................................................2 Referencing an Entity in Your Application....................................................................... 3 Supporting Multiple Locales..............................................................................................3 Further Reading..................................................................................................................4

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Localization

1. Overview
Firefox, and the various other Mozilla browsers, have a large and diverse community of users. Preparing your extension for localization is important because users prefer to use applications in their own language and culture. An extension is constructed of one or more source files, which are either interface files (XUL) or script files (JS). These source files contain references to textual data such as labels and buttons. While it seems natural to place ordinary strings in these source files, it will make it harder for people who use different languages. In fact, nothing stands out more to a user then to have some parts of a program use a language different from his or her system settings. To be a professional extension developer, it is essential to store textual elements, called entities, in a language file.

2. Entities as String Constants
Many applications are built such that translating the interface into a different language is as simple as possible [1]. In general, building translatable software is as easy as placing all textual data in a resource file as string constants and then referencing those constants from within the source code. In XML, a constant is known as an Entity. The XML syntax for declaring an entity is simple, but different than might be expected. The tag starts with “!ENTITY” followed by two parameters, the name of the tag and the string value associated with that tag. The XML parser will replace all occurrences of the tag with the associated string value.
<!ENTITY TagName "String Value">

Again, notice the syntax of the declaration. There is no trailing slash. In the context of an extension, the Entities are stored in a DTD file, which brings us to the next section.

3. Language Document Template Definition (DTD)
Consider the following Entities from the hpsched.dtd, located in the locale/en-US/ file:
<!ENTITY <!ENTITY <!ENTITY newSchedule.button editSchedule.button deleteSchedule.button "New Schedule"> "Edit Schedule"> "Delete Schedule">

For an extension, the locale folder contains one or more languages in various directories named after the ISO language codes such as en-US, en-UK, fr, es, etc. Say, for example, that

Page 2

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Localization

someone wanted to translate the Home Page Scheduler extension into Spanish, he would copy the hpsched.dtd file to locale/es/ and translate the string values, such as:
<!ENTITY <!ENTITY <!ENTITY newSchedule.button editSchedule.button deleteSchedule.button "Cree el Horario"> "Redacte el Horario"> "Borre el Horario">

By keeping the textual elements defined as constants within the DTD file, it is easy for translators to convert the application to support various languages without modifying code. As an extension programmer, you can focus on writing an awesome application and others can translate it to work in Catalan, Dutch, Japanese, and numerous other languages that you do not know. You may note that the translation in this example was conducted using machine translation from freetranslation.com. In general, it is a good idea to have someone who knows a particular language perform the translation. So by keeping the code and textual data separate, you can make the extension better for everyone.

4. Referencing an Entity in Your Application
Now that you are convinced of the importance of allowing easy localization [3] of your extension, it is time to see how to reference an entity from source files. To dereference an Entity in a source file, simply escape include the tag name like &TagName;. The ampersand (&) tells the parser that a tag name is to follow and the semicolon (;) ends the tag. The following XUL code declares three buttons with labels defined in the DTD file for the system's language.
<button label="&newSchedule.button;" oncommand="newSch();"/> <button label="&editSchedule.button;" oncommand="editSch();"/> <button label="&deleteSchedule.button;" oncommand="delSch();"/>

So now, if someone were to be using the Home Page Scheduler extension in Firefox on a Catalan system, the ca/hpsched.dtd file would be used instead of the en-US file. Sadly, at this time our extension does not have a Catalan-language directory, which means a Catalan-speaking user's system would default to the Spanish (if it existed) or to the available English strings.

5. Supporting Multiple Locales
Mozilla maintains extension code as a package in the chrome registry. There are usually three different parts to a chrome package, although they are all optional. Each part is stored in a different directory. These three sets are the content, the skin and the locale. A particular package might provide one or more skins and locales, but a user can replace them with their

Page 3

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Localization

own. In addition, the package might include several different applications each accessible via different chrome URLs. The packaging system is flexible enough so that you can include whatever parts you need, and allow other parts, such as the text for different languages [4]. The locales directory can hold one or more language DTD files. Copying the initial language file into a new directory and then translating the String Values are the several Entities defined within the DTD file creates a new language. The browser will select the best match for the user system's language setting.

6. Further Reading
1. XUL Tutorial: Localization. Devmo 2005 [cited November 5, 2005]. 2. ISO 639: Code for the representation of names of languages. 1990 [cited November 6, 2005]. 3. How to localize Mozilla. 2005 [cited November 6, 2005]. 4. XUL Structure. XUL Planet Tutorial 2005 [cited November 6, 2005]

Page 4

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Distribution
Table of contents
1 2 3 4

Overview............................................................................................................................2 Packaging........................................................................................................................... 2 Distribution........................................................................................................................ 2 Further Reading..................................................................................................................3

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Distribution

1. Overview
Congratulations! If you are to this step you must have something working! In order for you to share your extensions with others you will first need to package the extension. After all you have gone through, this will be quite easy!

2. Packaging
Simply follow these two steps to package your extension: 1. Open up your 'MyExt' folder and create a zip file containing all of the files and folders. Note that you should not zip up the MyExt folder itself, instead zip of the files and folders that are inside it. 2. Rename the file extension from .zip to .xpi. The name of your .xpi file does not matter; just pick something that makes sense to you. To test your package you can simply drag the .xpi file into your Firefox browser. Once you let go of the file, Firefox should recognize it as an extension and ask you if you would like to install it. Say yes! Your Firefox extension will be unverified and thus will make you wait a few seconds before you can install it. This is to ensure you understand there could be bad code within the file. Verifying your extension requires a lot of work that is beyond this tutorial (it is quite expensive, too).

3. Distribution
The best way to distribute your new Firefox extension is through Mozilla's developer website. The "Developer Control Panel" allows you to add/remove new versions of your extension, add/remove screenshots, update the compatibility information, and more. Most importantly, users will be able to download and install your extension through the built-in extension retrieval system. The URL is http://addons.mozilla.org/developers/. You will need to register with Mozilla to be able to use this service. Click "Join Mozilla Update!" in the bottom right hand corner to register. You will need to check your email to complete the registration process (the email was sent immediately for us). Once you are logged in you will have the opportunity to upload your new extension. Please note that it will take several days for your extension to be approved by Mozilla, this limits how much 'junk' can be posted to the website. Once accepted your new Firefox extension will be available along with other developers' extensions at https://addons.mozilla.org/extensions/?application=firefox. You can also find

Page 2

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Distribution

this website through Firefox by clicking Tools, then Extensions, and then clicking the "Get More Extensions" link. If you choose to host your Firefox extension on your own website, make sure that you serve it as application/x-xpinstall (this will be the default on most servers). This will allow people using Firefox to automatically install your new extension just by clicking the link!

4. Further Reading
Mozilla Developer Control Panel: https://addons.mozilla.org/developers/

Page 3

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Security
Table of contents
1 2 3 4 5 6

Writing Secure Code..........................................................................................................2 Prevention.......................................................................................................................... 2 Bugs, Flaws, and Vulnerabilities....................................................................................... 2 Lessons from the Greasemonkey Security Flaw................................................................3 Important Concepts............................................................................................................ 4 Further Reading..................................................................................................................4

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Security

1. Writing Secure Code
Anytime an application (such as Firefox) allows user code to execute without being validated can open up security vulnerabilities. As a developer it is your responsibility to ensure that your extension does not open any vulnerabilities to the Firefox browser. While most extension code is JavaScript, it has significantly more permissions than ordinary JavaScript found on a website. For example, JavaScript within an extension that is registered with the Mozilla Chrome registry has access to the local file system. When building a new extension, you should take into security concerns from day one. Users should also be cautious when downloading and installing extensions. Fortunately, now that you know how to develop extensions, you can spend time reading through the source code of an extension before you choose to install it on your computer!

2. Prevention
Maintaining a secure browser is important business. The Firefox source code is maintained by a large number of developers and reviewed by many security experts. However, a particular extension is less likely to be reviewed by as many people. Unfortunately, a vulnerability in an extension is also a vulnerability in the browser that exposes all users to potential harm. Once attacks are developed for a vulnerability they spread rapidly over the Internet and can often be used for nasty things such as identity theft. While more attention is generally given to security after something bad happens, an ounce of prevention is worth a pound of cure (Building, 19). After you have finished your extension, you should monitor the various security reporting mailing lists and databases, including Bugtraq, CERT Advisories, and the RISKS digests. Look for vulnerability reports for similar extensions and premptively fix similar problems in yours.

3. Bugs, Flaws, and Vulnerabilities
To understand the risk in any given software system, it is important to consider how vulnerabilities are identified and exploited. Problems arise in the presence of a software bug or design flaw, which are often the result of inaccurate assumptions. There is an every growing volume of online documentation and some very good books on topics of exploiting software and building secure software. It is important to be familiar with these topics and learn from historical exploits because "related programming errors give rise to similar exploit

Page 2

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Security

techniques" (Exploit, 38). A software exploit takes advantage of a vulnerability to cause the program to do something that it was not intended to do. For example, it may allow an attacker to gain access to a user’s private information and make changes to someone else’s computer system. One of the most dangerous forms of attack is called an arbitrary code execution, which can allow spy-ware and viruses to be installed and many nasty things. Bugs and flaws in a piece of software cause vulnerabilities. A bug is a software problem that is caused by simple implementation problems, such as not explicitly initializing a variable or misusing a system call. Whereas a bug can often easily be fixed by code modifications, a flaw is a much deeper problem. A flaw is a design decision that can be exploited despite implementation.

4. Lessons from the Greasemonkey Security Flaw
Greasemonkey is a popular Firefox extension that allows you to create scripts that can add new features to a page, remove features from a page, fix a page that is broken, or add data from other websites to a page. For example, a lot of people use Greasemonkey to insert a Delete button next to the archive button in Gmail. Some of the GreaseMonkey user scripts affect specific sites, some can affect other extensions, and some can apply to all sites. This kind of powerful manipulation has serious security implications and you can totally screw up the visuals of certain websites. However, the developers of the extension really didn't consider the security angle too much. They had a real relaxed attitude about it. Aaron Boodman, one of the developers, said: "User scripts run in content's security context. I don't see any possible problems". However, Mark Pilgrim, one of the main early adopters of GreaseMonkey disovered a huge security hole that would allow data to be leaked to remote sites. This was a huge embaressment intially to the developers of GreaseMonkey as well as the open source community. It became a big deal and users were advised to downgrade their version of Firefox. Slashdot also ran a story about the whole ordeal. The open source community had also traditionally touted that open source software was inherently secure because the open source process makes it so through collaborative culture that makes people check each other's code. Even though Firefox itself was not the culprit, the extension itself exposed way too much of users' computers via poorly-implemented APIs. There were several lessons to be learned from this development debacle. Firstly, just because the overall browser is secure doesn't mean the extension automatically is going to be secure. A disciplined approach to reducing the attack surface area is necessary. Secondly, after a vulnerability has been exposed, being open about it and confronting the issue head on allows information to given to those who need it, such as developers, IT folks, users, and security
Page 3

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.

Firefox Extension Development Tutorial :: Security

pros. This was one of the nice things about the way Boodman handled the flaw in his extension. He updated the Mozilla extension website to warn users, conducted an open mailing list, and sought advice from people who were willing to help. Your reaction after finding a flaw is also as important as taking measures to prevent them.

5. Important Concepts
The following outline includes some important security concepts, without explaination. All of these topics are covered in depth in Building Secure Software. It is a good idea to look through the Internet and the resources listed at the end of this article. • Principle 1: Secure the Weakest Link • Principle 2: Practice Security in Depth • Principle 3: Fail Securely • Principle 4: Follow the Principle of Least Privilege • Principle 5: Compartmentalize • Principle 6: Keep it Simple • Principle 7: Promote Privacy • Principle 8: Remember That Hiding Secrets is Hard • Principle 9: Be Reluctant to Trust • Principle 10: Use Your Community Resources

6. Further Reading
• • • • • • • [Exploit] Greg Hoglund and Gary McGraw, Exploiting Software: How to Break Code. Addison-Wesley Professional, 2004. [Building] John Viega and Gary McGraw, Building Secure Software: How to Avoid Security Problems the Right Way. 2001: Addison-Wesley Professional. Mozilla Security Security Focus SecurityFocus on Handling of Greasemonkey Security Flaw Firefox Greasemonkey Extension Disclosure of Sensitive Information CAN-2005-0399 - Firefox/mozilla gif extension heap overflow

Page 4

Copyright © 2005 LCC 3401 Firefox Group All rights reserved.


				
DOCUMENT INFO
Shared By:
Stats:
views:261
posted:8/15/2009
language:English
pages:39
Description: How to Create a new Firefox Extension and Installation, illustrates clearly. This is very helpful article for developers want to create their own extensions for Firefox browser.