Chapter 6. Packaging and Installing Applications

The previous chapters covered the basic parts of building an application. Now that you've seen how to create an application with XUL, CSS, and JavaScript that can be used on your local computer, we will show you how to turn your program into something that can be installed by other users. This chapter discusses the technologies Mozilla provides for packaging and installing applications.

Until your project is packaged for distribution, it can't be fully considered a finished application (unless it was designed to work only on the computer where it was created). Making your application distributable, installable, and registrable allows others to use what you have created.

This chapter is divided into four main sections. It starts with a quick overview of the basics of packaging and installing applications. The second section provides details about how to get your application packaged and described so that Mozilla recognizes what it is. The next section specifies how to put your package into a cross-platform installation file that can be installed over the Web onto other machines. The last section provides tips for customizing how your application will look once it is installed.

6.1. Packaging and Installing Overview

Several different pieces comprise Mozilla's distribution technology. In fact, Mozilla may have a few more moving parts than other packaging systems because it needs a way to package and install new software uniformly across several different platforms. Figure 6-1 shows the major components of Mozilla's packaging system outlined in black.

Figure 6-1. Mozilla packaging components


As you can see in Figure 6-1, the Cross-Platform Installer (XPI), pronounced zippy or X-P-I, is the archive format used to distribute Mozilla applications. The XPI file contains a script that downloads and installs the application. The package inside the XPI has a manifest that is used to register the new Mozilla-based software with the Mozilla chrome registry.

When a XPI contains a Mozilla-based package such as the xFly sample discussed in Chapter 2 and the following chapters, the installation script also takes care of the package registration process, described in the Section 6.2.2 section later in this chapter. A Example 6-1 shows a simple installation script and the kind of information it contains. The Section 6.3.2 section, also later in this chapter, discusses other scripts that may need to be used in the installation process, such as trigger scripts.

Example 6-1. Package installation script
var myFile = "xFly.jar";
initInstall(                      // initialize the installation
  "Install xFly",                 // display name of installation
  "xFly",                         // package name
  "0.0.1",                        // version of install
1);                             // flags - an optional argument,
                                  // reserved for future use
f = getFolder("Chrome");          // specify a target directory
addFile(myFile);                  // add software to the installation
  PACKAGE | DELAYED_CHROME,       // chrome switch (i.e., type)
  getFolder("Chrome","xFly.jar"), // destination of package
  "content/xFly/");               // location of manifest in package
if (0 == getLastError( ))         // if there have been no errors:
  performInstall( );              // install "xfly.jar"
else                              // otherwise
  cancelInstall( );               // cancel the installation.

The installation process requires a few different steps. First an installation must be initialized. Then the software to be installed is added to the specified target directory. Finally, packages in the installation are registered. At this point, the application is installed on a user's computer.

When you install new packages or Mozilla-based software, the chrome registry on the Mozilla side brokers the deal -- reading the manifest, executing the installation script(s), and updating the package information that it maintains internally (storing this information using RDF).

The relationship of the packaging, installation, and registration -- and all pieces involved -- may seem a little complex and idiosyncratic at first, but bear with it. The upshot of this powerful but somewhat diffuse packaging technology is that you can bundle your software, put it on a server, and have users install it by simply clicking a link on a web page when using Mozilla.

It is possible to use this packaging system to bundle any sort of application or extension to an existing Mozilla application. You can install a XPI that adds functionality to the Mozilla browser, such as Mouse Gestures (, which enables the execution of common browser commands with mouse movements. You can package new Mozilla development tools and libraries like JSLib (see Chapter 5). You can also create installations for entirely new Mozilla applications.

6.2. Packaging Mozilla Applications

Packaging simply means organizing your files into a Mozilla application structure. Packaging your application is required to make it installable and to make it something that Mozilla recognizes as one of its own. Whether your Mozilla-based becomes a part of an existing Mozilla application, like Mouse Gestures, or will exist as a standalone application, like JabberZilla, you will need to package it.

When you are done with this packaging section, package your Mozilla-based applications in the same way that we packaged the xFly example in Chapter 2. This chapter describes the manifests and other necessary files. Then the Installation section shows how you can put your package in a XPI file and create installation script(s) so it can be distributed and installed.

6.2.1. Package Manifests

All new packages must have manifests describing their contents, skin information, and locale information. These manifests are formatted in RDF, which makes them easy to combine with the RDF data that makes up the chrome registry and makes it easy to fit the package into the Mozilla software. There is some flexibility about where in the package the manifest must appear, but the registration process must find and read it regardless of where it is.

The installation script points out the manifest locations so the package can be registered properly. Note that manifests appear in JARs, but they do not appear in XPIs, since the latter is a temporary file that gets deleted once the files it contains, including JARs, are installed (see the Section 6.3 section later in this chapter for more information about XPI install files). Theme package manifests

Example 6-2 shows a manifest for a new theme to be installed in Mozilla. It is simple because it describes only one type of package, the “pfly skin,” and the existing component it interacts with, the communicator -- the default Mozilla browser (the syntax and structure is the same for all manifests, however). The manifest says, in effect, this is what I have here (the metadata about the theme -- its name, a description, etc.), and this is what it affects (the list of chrome:packages to which the theme should be applied).

Example 6-2. Simple theme package manifest
<?xml version="1.0"?>
<RDF:RDF xmlns:RDF=""
  <!-- List all the skins being supplied by this theme -->
  <RDF:Seq about="urn:mozilla:skin:root">
    <RDF:li resource="urn:mozilla:skin:flyskin/1.0" />

  <!-- Fly Skin Information -->
  <RDF:Description about="urn:mozilla:skin:flyskin/1.0"
    chrome:displayName="Fly Skin"
    chrome:description="shimmering, purple/black, hairy">
     <RDF:Seq about="urn:mozilla:skin:classic/1.0:packages">
       <RDF:li resource="urn:mozilla:skin:classic/1.0:communicator"/>
</RDF:RDF> Language pack manifests

When you look at a package manifest that describes a new locale, as shown in Example 6-3 (which is for a German language pack in Mozilla), you see a similar structure. Again, the manifest describes the new package first and then lists the existing components to which this new package applies.

Example 6-3. Locale package manifest
<?xml version="1.0"?>
<RDF:RDF xmlns:RDF=""
 <!-- list all the skins being supplied by this package -->
 <RDF:Seq about="urn:mozilla:locale:root">
 <RDF:li resource="urn:mozilla:locale:en-DE"/>
 <!-- locale information -->
 <RDF:Description about="urn:mozilla:locale:en-DE"
  chrome:displayName="English (German)"
   <RDF:Seq about="urn:mozilla:locale:en-DE:packages">
     <RDF:li resource="urn:mozilla:locale:en-DE:communicator"/>
     <RDF:li resource="urn:mozilla:locale:en-DE:editor"/>
     <RDF:li resource="urn:mozilla:locale:en-DE:global"/>
     <RDF:li resource="urn:mozilla:locale:en-DE:messenger"/>
     <RDF:li resource="urn:mozilla:locale:en-DE:navigator"/>

Note that in Example 6-3's package manifest, all major components are affected by this new locale package. When the package is installed and the manifest is read, the chrome registry is made aware of a German language pack that it can use to display German in the interface of each Mozilla component.

contents.rdf Type Manifests

Package manifests are an area where Mozilla browser itself may not be the best model for learning about the best application development practice. Mozilla is such a large and modular application that it uses several manifests instead of one application-wide manifest.rdf file.

Although they have the same format, these distributed manifests are found in several contents.rdf files. In a single theme (e.g., the modern.jar), you can see as many as eight manifests (for major component to which the theme applies).

These two types of manifests -- the contents.rdf file, which typically describes a single package-component relationship; and the manifest.rdf file, which describes the package's relationship to all affected components -- are functionally equivalent. In both cases, the chrome registry reads all RDF/XML data and registers the package.

Because the manifest data format is RDF/XML, you can use either type of manifest in your own package development, although using a single manifest.rdf is generally much easier, especially if you want to change the list of affected components of any other metadata later.

The package manifests for content and new applications -- which may include new content, skin, and locale information -- have an identical syntax and a very similar structure, as you will see in the following sections. The manifest for a full Mozilla-based application like xFly describes the content, the skin, and the locale in a single file that sits at the top of that package. Application manifests

When you create new applications on top of Mozilla, you will often create new content, new skins, and your own localizable language elements, such as DTDs. For applications, the manifest must describe these parts of your application if Mozilla is to find and register them properly.

Example 6-4, the package manifest from the XMLTerm Mozilla extension, describes the contents, skin, and locale in a single file, which is most common for Mozilla-based applications.

Example 6-4. manifest.rdf describing the XMLTerm extension
<?xml version="1.0"?>
<RDF:RDF xmlns:RDF=""
  <!-- list all the packages being supplied by this jar -->
  <RDF:Seq about="urn:mozilla:package:root">
    <RDF:li resource="urn:mozilla:package:xmlterm"/>
  <RDF:Seq about="urn:mozilla:skin:root">
    <RDF:li resource="urn:mozilla:skin:modern/1.0" />
  <RDF:Seq about="urn:mozilla:locale:root">
    <RDF:li resource="urn:mozilla:locale:en-US"/>
  <!-- xmlterm package information -->
  <RDF:Description about="urn:mozilla:package:xmlterm"
  <!-- xmlterm overlay information -->
  <RDF:Seq about="urn:mozilla:overlays">
    <RDF:li resource="chrome://communicator/content/tasksOverlay.xul"/>
  <RDF:Seq about="chrome://communicator/content/tasksOverlay.xul">
  <!-- locale information -->
  <RDF:Description about="urn:mozilla:locale:en-US"
      <RDF:Seq about="urn:mozilla:locale:en-US:packages">
        <RDF:li resource="urn:mozilla:locale:en-US:xmlterm"/>
  <!-- xmlterm skin information -->
  <RDF:Description about="urn:mozilla:skin:modern/1.0"
      <RDF:Seq about="urn:mozilla:skin:modern/1.0:packages">
        <RDF:li resource="urn:mozilla:skin:modern/1.0:xmlterm"/>

The structure in Example 6-4 is exactly the same as that in more focused manifests (Example 6-2 and Example 6-3), but all of the skin, content, and locale structures sit together in a single manifest.rdf file. This manifest follows the Mozilla convention of introducing the package contents at the top and then expanding upon the basic listing of each separate sections, providing the necessary metadata about the items in the middle, and then listing the components that are affected by the items at the end. However, the flexibility of the RDF format means you could just as easily order this information differently -- which is why RDF is sometimes described as creating a “soup” of statements about resources.

Note that the overlay section in the middle of the example is part of the content description. It tells the chrome registry that the contents of the file xmltermOverlay.xul should be overlaid into the tasksOverlay.xul file in Mozilla, in which much of the Tools menu is defined. The package manifest for the xFly sample application that we discuss here, also a single file, is very similar to the manifest in Example 6-4.

6.2.2. Registering Packages

Typically, registration occurs during installation, which is why the Section 6.3 section of this chapter goes into more detail about the specific methods and objects available for package registration. The registration process deals with packages and package manifests, however, so the following two sections describe the two types of package registration that are possible in Mozilla. The first provides an overview of how to register a package on installation, as is typically done, and the second describes how to use a special file to register your work with Mozilla as you develop it so that you can view your work as it progresses. Registering packages on installation

Generally, the registration process is a transaction that takes place between your installation scripts, the chrome registry, and the manifests that describe the package. Usually, registration happens upon installation. You can approach this transaction in many ways, but the general relationship is shown in Figure 6-2.

Figure 6-2. Package interaction overview


In this relationship, the install script is responsible for managing the transfer of files to a specified location on the local disk and alerting the chrome registry to the new files and their manifests. The chrome registry then finds and reads those manifests. If the information there is formatted correctly, then that information is added to the sum of package information that the chrome registry manages -- a single, overarching datasource of all packages in Mozilla, including skins, locales, overlays, and other software. In this way, the package is added to Mozilla. The major players in this interaction between the packages, the package descriptions, and the chrome registry are shown in the following list.

  • Manifests in the archives themselves
  • XPInstall, the technology that performs the downloading and resource installation
  • The chrome registry, the database of packages, and user information that is read and written to when new software is installed Registering packages as you develop them (installed-chrome.txt)

The file installed-chrome.txt is a convenience for developers who want to create and test new packages without having to install them with installation scripts and manifests. Some earlier xFly examples in this book already used this method. The installed-chrome.txt file is a list of entries that point to package manifests. Each line provides the chrome registry with a pointer to a manifest in which new software is described: new skin information, new packages, and new locales.

In the following snippet from the installed-chrome.txt file in the Mozilla chrome directory, five entries point to contents.rdf type manifests that describe the modern skin resources particular to the application's major components. The first line in this list, for example, tells the chrome registry to find a contents.rdf file in the subdirectory skin/modern/communicator contained in the modern.jar file, which describes the resources present there to skin the communicator component. When the chrome registry reads this line, it uses those resources to skin the communicator component, shown here:


Instead of installing your package with installation scripts, you can add the appropriate entries to this file, as seen in the following examples. Adding these entries only registers local content on your machine. When you use the installed-chrome.txt file, you neither install a new package nor make that package installable by others. Editing the installed-chrome.txt file directly is a shortcut for making Mozilla aware of packages so that you can check your progress as you develop. You probably need to create an installer for packages you want to distribute and install on other systems.

To register a local copy of the xFly application with the Mozilla chrome directory, you would add the following three entries, where the xFly directory and the appropriate subdirectories sit directly under the chrome directory:


The first line tells the chrome registry that the content is found in the directory chrome/xfly/content. The next line points to the skin resources at chrome/xfly/skin, and so on. Note that creating a single entry for the xFly skin and locating its resources underneath the xFly application directory (as opposed to a subdirectory in the modern and/or classic JARs) means that the xFly skin will not change when the user changes skins.

If we had the same structure archived in a JAR file called xfly.jar rather than in a directory, the installed-chrome.txt entries would look like this:


This code tells the chrome registry to look in the content, skin, and locale/en-US directories in the JAR file to locate the manifests.

This skin entry seems to indicate that only one set of skin information is available for the xFly sample, and that it always applies. If the xFly skin inherits, as many skins do, from one or another of the preinstalled theme (e.g., Modern), it may look very bad or even break when that theme is not selected. See the section Section in Chapter 4 for a discussion of skin inheritance and tips on how to make sure your skin is structured to best take advantage of it.

When you make these additions to the installed-chrome.txt file and restart Mozilla, the chrome registry looks for manifests in the directories you specify and registers the packages described there. The installed-chrome.txt entries in this section do not necessarily need to be included on your final XPI resource, but you will see them in some XPIs bundled in their own installed-chrome.txt file separate form the main one. See the section Section 6.2.4 for more information about this process.

6.2.3. Creating a Package

The xFly sample package is a relatively straightforward arrangement of content, skin, and locale. You have already seen how to set up most preliminaries you need to make it a package in Chapter 2, but this section will discuss the process in detail. Setting up xFly

To start working immediately with tools like XUL and CSS, you can move some things around and hack one of the chrome registry files, as you have already seen. This section reviews those important preliminary application development steps in more detail.

Because it has its own interface and is not worried (for now) about being made available in languages other than English, the only one for which it has a language pack, the xFly package is self-contained:


All parts of the package can be held in a single JAR file or a single chrome subdirectory. Contrast this with a large component-like communicator that, when you include its content, skin, localized information, and the Mozilla services it uses via XPConnect, is spread out into all of the main JAR files that make up the distribution:


When you develop your application, it's typical to work within a regular directory. As you finish the application and make it available for distribution and installation, however, you may want to use one of the installation archive formats to package your work, such as a JAR file. See the section Section 6.3.1 later in this chapter for more details.

When your application is large and distributed in this way, the RDF-based manifests “compose” all of the metadata and treat all files as a single component. Hacking the installed-chrome.txt file

The entries you made to the installed-chrome.txt in Chapter 2 tell the chrome registry that a new package must be registered:


These entries tell the chrome registry that, in addition to all of the packages that make up the main Mozilla browser (e.g., the communicator skin in the Modern theme, the en-US locale, and the content that makes up the navigator), the xFly content, skin, and locale should be registered as components of a new package. When the chrome registry reads these entries, it tries to find the manifests for these parts of the xFly package. When it finds them, it registers the package, overlays any files it finds in that package (see the next section), and makes it accessible via the special chrome:// URLs given in the manifests. Adding the xFly application to the Mozilla Tools menu

Adding your application to one of the Mozilla browser menus (so users can easily launch your application once it is installed) makes your application feel official. Figure 6-3 shows the presence of the xFly item in the Tools menu. The Tools menu lists various extra components in Mozilla, including the DOM Inspector and the JavaScript Debugger (if they are installed).

Figure 6-3. xFly item in Tools menu


It is also possible to add an item to the Window menu that includes links to Navigator (the default browser), the Mail and Newsgroup client, the Chatzilla IRC client, Composer, and the Address Book (which only show up if they were added as part of the Mozilla installation process or if they were added separately afterwards).

Here we describe how you can use special constructions in your package's manifest to tell the chrome registry about files from your package that should be overlaid into the main browser. Overlaying these files lets you add interface items, such as this link to xFly, in an existing application. Example 6-5 shows the simple overlay file that puts xFly in the Tools menu.

The top-level element is an <overlay/> rather than a <window/>. Direct children of the overlay are associated with certain elements in the main browser (in this case, the <menupopup/> of the Tools menu) and their contents are interpolated into the list of children there. This file overlays an extra <menuitem/> into the Tools menu. In this case, the menuitem has an oncommand event handler that calls toOpenWindowByType -- a function for opening new chrome defined in the tasksOverlay.js that much of the chrome in the Mozilla UI imports.

Example 6-5. The xFly overlay
<?xml version="1.0"?>
<overlay id="xflyTasksOverlay"

  <menupopup id="taskPopup">
    <menuitem label="xFly"
        oncommand="toOpenWindowByType('xfly:main', 'chrome://xfly/content/');" />

But how does the overlay know where to overlay itself? The IDs of the overlay children and the original XUL are matched to find the target within the files, but the manifest that accompanies the overlay in your package tells Mozilla which overlays are associated with which XUL files. The part of the manifest that deals with an overlay looks like the code in Example 6-6. This code is put in the contents.rdf file in the content directory of the xFly package.

Example 6-6. Overlay information in the manifest
<!-- overlay information -->
  <RDF:Seq about="urn:mozilla:overlays">
    <RDF:li resource="chrome://communicator/content/tasksOverlay.xul" />
  <RDF:Seq about="chrome://communicator/content/tasksOverlay.xul">

The first RDF element in the manifest is a list of affected target files and the second is a list of files that should be overlayed into those targets. Do not be confused by the names of the files in this case: the tasksOverlay.xul file is a target -- though it is an overlay, as described in the following section -- and xflyOverlay.xul is the overlay with the xFly menu item. Overlaying Mozilla files into your application

In the previous section, we described how to use the XUL overlay technology to put information from your application into the Mozilla browser. When developers use overlays in this way, they usually add a menuitem or a new UI to the browser that provides access to the application.

But overlays can also add interface elements and other data from Mozilla into the application itself. In fact, each component in Mozilla imports a lot of its own user interface from such XUL overlay mainstays as globalOverlay.xul, tasksOverlay.xul (the file into which the xFly menuitem is overlaid), and navigatorOverlay.xul. As you can see when you look at the main browser file, navigator.xul, shown in Example 6-7, most user interface is actually brought in from these reusable overlays. A relatively small percentage of all that appears in the browser is defined within that particular navigator.xul file.

Example 6-7. Overlays in navigator.xul
<?xul-overlay href="chrome://navigator/content/navigatorOverlay.xul"?>
<?xul-overlay href="chrome://navigator/content/navExtraOverlay.xul"?>
<?xul-overlay href="chrome://navigator/content/linkToolbarOverlay.xul"?>
<?xul-overlay href="chrome://communicator/content/sidebar/sidebarOverlay.xul"?>
<?xul-overlay href="chrome://communicator/content/securityOverlay.xul"?>
<?xul-overlay href="chrome://communicator/content/communicatorOverlay.xul"?>
<?xul-overlay href="chrome://communicator/content/bookmarks/bookmarksOverlay.xul"?>

Of these overlays, those with the most value for application developers are the communicatorOverlay.xul, which defines many of browser menus; the tasksOverlay.xul, which adds the Tools menu and brings in all of its application menuitems as well as a lot of important browser functions like toOpenWindowByType and toNavigator (for returning to the main browser window); and the globalOverlay (which is overlaid into navigatorOverlay.xul, so it gets loaded there), which defines even more general and low-level features like pop ups and functions for quitting the application or setting tooltip text.

Once files are divided into subdirectories and the manifests for each subdirectory, your application is technically a package -- although until you compress it and create an install script, it's a package only for your computer and the environment in which it was created. See the section Section 6.4 later in this chapter to see how you can use the file format and installation information to make the xFly something you can put on a web server and have users install with a single click on a web page.

6.2.4. The Chrome Registry

The chrome registry was briefly mentioned several times in this book. It plays an important (but sometimes invisible) role in the way Mozilla applications, including the Mozilla browser itself, deal with user information, new components, skins, and other resources.

At the beginning of the book, you had to create RDF files that would describe your application to Mozilla. Special entries also needed to be made to the installed-chrome.txt file in the chrome application directory. These entries are just two of the most common ways to address the chrome registry, which is what Mozilla uses to persist configurable aspects of the browser and its other applications. Where is the chrome registry?

The chrome registry is not a single file and it's not stored in a single place. Rather, it is a distributed collection of data and interfaces for data manipulation. The data itself generally lives in RDF files, many of which are in the chrome application directory. The chrome registry APIs -- principally nsIChromeRegistry -- are used by installation scripts when they register new software, by the skin-switching UI, and by the language selection facility. The chrome registry is the means through which packages are registered.

In some cases, especially when you create and debug your Mozilla application, you may want to edit the RDF files that make up the chrome registry directly. But more often, you can use external scripts, inline JavaScript, or the installed-chrome.txt file to get what you need from the registry. Procedures for doing so are described in the section Section 6.2.2 earlier in this chapter, and in the section Section 6.3.2 later in this chapter. Accessing the chrome registry in installation scripts

An install script is a required part of a software package like the xFly. The two main functions of an installation script are the physical download and installation of files in the package and registration of that software with the chrome registry. Install scripts use functions from the XPInstall API to install the files and functions from the chrome registry interface to handle the latter, as seen in this snippet:

registerChrome(PACKAGE | DELAYED_CHROME, getFolder("Chrome", "help"), "content/");

The registration process is typically something that happens between the install initialization and the actual execution of the install:

initInstall( ) // initialize the overall installation
// add items to installed using:
// addFolder, addDirectory, getFolder, and others
registerChrome(TYPE, dir, subdir)
performInstall( );

Scripts and the installation process, including the registration of installed packages, are detailed in the next section.

6.3. Installing Mozilla Applications

Once your application is packaged, the next step is to create a cross-platform installation, or XPI. A XPI is a special file archive that contains your Mozilla package(s) and its own installation instructions. The relationship of the various parts of the installation process -- the XPI itself, the internal installation script, the trigger script that begins the installation, and the Mozilla browser -- can be visualized in Figure 6-4.

Figure 6-4. Installation process overview


6.3.1. The XPI File Format

Mozilla cross-platform installations use XPIs as the file format in which to organize, compress, and automate software installations and software updates. A XPI is a PKZIP-compressed archive (like ZIP and JAR files) with a special script at the highest level that manages the installation. A quick scan of the contents of a XPI file (which you can open using with any unzip utility) reveals the high-level directory structure shown in Example 6-8.

Example 6-8. Top level of the browser.xpi archive

Note that the high-level structure in Example 6-8 parallels the installed browser's directory structure very closely. The bin directory at the highest level of the archive corresponds to the Mozilla application directory. On Unix, this directory is actually called bin, where all of the resources are stored. On other platforms, the installation puts these resources in the application directory itself.

In the case of the Mozilla browser, the XPIs manage the transfer and registry of all components -- the chrome files in the JARs, the executables, the default user information, and the libraries. As you will see in the installation script, the contents of the archive are installed onto the filesystem in much the same way as they are stored in the archive itself, although it's possible to rearrange things arbitrarily upon installation -- to create new directories, install files in system folders and other areas, or execute software that handles other aspects of the installation, such as third-party installers. XPI example

When the items to be installed are very simple, XPIs may contain nothing more than a single executable and the install script itself, as shown in Figure 6-5. In this figure, the WinZip utility has been used to display the contents of a XPI that installs a text editor on a Win32 system.

Figure 6-5. Simplest XPI archive


This example uses XPInstall technology to install something that may or may not be a Mozilla application. The install.js script in Example 6-8 would look like this. In Mozilla application development, however, XPIs often contain JAR files that are installed as new packages in the Mozilla distribution. To make a XPI for your package, use any zip software (applications or extensions that will be part of the main Mozilla distribution are required to use the free zip utility from InfoTools so that they can be run as part of the build process) to archive your files. JARs versus XPIs

Technically, only the internal installation script distinguishes JARs and XPIs. However, Mozilla treats them differently. Since JARs do not include this installation script, they cannot install full content or applications by themselves. In this case, "content" means XUL, XBL, or JavaScript files that have script access to XPCOM. Files of this kind that are in JARs are denied access to XPConnect and are not registered as content in the chrome registry. JARs are used primarily to install locales, or language packs, and skins.

Skins that contain scripts and bindings (see the section Section 4.5.3 and the Evil Skins sidebar, both in Chapter 4) are seen more as chrome content and must be installed in XPIs if they are to be fully functional. Like executables that are fetched from the Web, XPIs can cause trouble when downloaded by unprepared users since the software in XPIs are given the same privileges on the Mozilla platform that the browser chrome itself has.

The characteristics and usage of an XPI are:

  • Has an install.js file
  • Can install anything via XPInstall API
  • PKZip-compressed
  • May contain one or more JAR packages
  • Mozilla installation
  • Used for new packages

The characteristics and usage of a JAR are:

  • Contains only the resources themselves
  • Installed with an external script
  • May be installed inside a XPI
  • PKZip-compressed
  • Themes
  • Languages packs
  • Storage archive for installed components

Mozilla uses the presence of this internal installation script and not the file suffix (which can be changed easily enough) to determine what type of archive it is. Accordingly, JARs are most often used to install new themes and new language packs, which can be done by using just a brief trigger script on a web page loaded into Mozilla. When they contain new chrome -- new XUL and JavaScript that will access the Mozilla objects via XPConnect -- JAR files must be put within a XPI that can register them properly.

6.3.2. Installation Scripts

Most new packages in Mozilla are installed by means of installation scripts. These scripts are written in JavaScript. Unlike regular web page JavaScript, however, which uses window as the top-level object, installation scripts have a special install object context. As you will see in the following examples, the Install object -- even when it's implicit and not prefixed to the object methods -- is the top-level object upon which most methods are called. Script examples

At their very simplest, installation scripts look something like Example 6-9.

Example 6-9. Simple install script
// initialize the installation first
initInstall("My Package Install", "package_name", "1.0", 1);
// add files to the installation
f = getFolder("Program");
// perform the installation
performInstall( );

These methods are being called on the Install object, which is implicit in an installation script. Example 6-10 is an equivalent (and still very compact) installation script. The Install object is prefixed explicitly to the install functions.

Example 6-10. Script that explicitly prefixes the Install object
Install.initInstall("My Package Install", "package_name", "1.0", 1);
f = Install.getFolder("Program");
Install.performInstall( );

As they become more complicated, install scripts may set up and arrange target directories in more specific ways, do more error checking, and include variables to make the code more readable and reusable, as seen in the longer install script in Example 6-11.

Example 6-11. A more complicated install script
var vi = "";
var xpiSrc = "adddir1";
initInstall("addFileNoVers1", "adddir_1", vi, 1);
f = getFolder("Program");
err = addDirectory(xpiSrc);
logComment("the error = " + err);
if (0 == getLastError( ))
  performInstall( );
  cancelInstall( ); Web page installations

XPInstall technology makes software installation from a web page very easy. When a link on a web page kicks off the installation of new software, “trigger” code on the web page starts the process and gets the XPI onto the local system. Once this is done, the install.js file in the XPI can take up the full installation and registration of new files.

In Example 6-12, the trigger script -- placed in an onclick event handler on the page -- starts the installation of a new theme on the local machine, where the XPI can be unpacked and its installation script executed in full.

Example 6-12. Trigger script on a web page
<a href="#"
   Install the New Blue theme</a>

Later, we discuss in more detail the Install object, whose methods are typically called in installation scripts. Scriptless installations

When you have a simple Mozilla package like a theme, which does not need special security privileges and which is always installed in a particular location, you can leave out the XPI and its internal installation script altogether and use a trigger script like Example 6-13 and a regular JAR file to download and register the new package.

Example 6-13. Scriptless install of a JAR
<a href="#"
   Install the New Blue theme</a>

The only difference here is that the item to be installed is a JAR and not a XPI file. Also, no internal installation script is present (since of the two, only XPIs carry their own install.js file). When the InstallTrigger object gets a JAR with a package manifest it can read and a package type that doesn't break the security boundary for applications (i.e., a new theme, a new language pack, or new content that doesn't use XPConnect), it can download and register that package with the chrome registry and make it available to users. The JAR and a trigger script like the one just shown are all you need in this case. See the earlier section, Section for more detail on the limitations of scriptless installs.

The xFly application accesses XPCOM objects in Mozilla, which makes it a full-blown XPConnected application. Thus, it needs to be installed in a XPI file that has its own internal installation script. Platform-dependent installation

Though the XPI format is by definition cross-platform, the files you distribute within it may need to be installed on a per-platform basis. The platform can be retrieved using the platform property of the Install object or the getFolder function. Example 6-14 shows a JavaScript function for install.js for returning the platform that the script is running on.

Example 6-14. Getting the operating system in an install script
function getPlatform( )
    var platformStr;
    var platformNode;
    if('platform' in Install)
        platformStr = new String(Install.platform);
        if (!^Macintosh/))
            platformNode = 'mac';
        else if (!^Win/))
            platformNode = 'win';
            platformNode = 'unix';
        var fOSMac  = getFolder("Mac System");
        var fOSWin  = getFolder("Win System");
        logComment("fOSMac: "  + fOSMac);
        logComment("fOSWin: "  + fOSWin);
        if(fOSMac != null)
            platformNode = 'mac';
        else if(fOSWin != null)
            platformNode = 'win';
            platformNode = 'unix';
    return platformNode;

It's often necessary to check the platform when you install new language packs. At the time of this writing, issues related to write access to the chrome folder on Unix systems require some forking in the install script. There are also certain JAR files that are installed on a per-platform basis in language packs. Example 6-14 covers the three major platforms (Windows, Mac, and *nix). Here is how you use it:

platformNode = getPlatform( );
if (platformNode != 'unix') {
  // do Unix script and files
else if (platformNode != 'win') {
  // do Windows script and files
else {  // mac
  // do Mac script and files
} The install log

When you are testing your XPI or need a way to troubleshoot installation problems, one of the best methods is to consult the installation log file. This file is called install.log and lives in the bin directory.

The install.log file is generated the first time you try to install software in Mozilla and appended to for each subsequent installation. The format of the file -- in which the URL and date of the installation appear as a heading -- makes it easy to find the installation you are checking on in the install log.

Example 6-15 shows the output in install.log after a single successful installation.

Example 6-15. install.log
-------------------------------------------------------------------------------  --  06/28/2002 19:12:59
     Install xFly (version 0.0.1)
     [1/4]    Installing: C:\MOZILLA\BIN\chrome\xfly.jar
     [2/4]    Register Content: jar:resource:/chrome/xfly.jar!/content/
     [3/4]    Register Skin: jar:resource:/chrome/xfly.jar!/skin/
     [4/4]    Register Locale: jar:resource:/chrome/xfly.jar!/locale/en-US/
     Install completed successfully  --  06/28/2002 19:13:03

In your install.js file, you can use the method logComment to create output other than these standard logging messages. This can be very useful for debugging your install scripts or providing extra feedback:

logComment( "Installation started ..." );

The output for this call will appear in install.log formatted like this:

** Installation started ...

When installation is not smooth, Mozilla outputs an error code to track down what is happening. For example, if you declare a constant variable twice in your install script, you will receive notification of an script error in the UI, and this error will be logged in install.log:

** Line: 4    redeclaration of const X_JAR_FILE
Install **FAILED** with error -229  --  07/01/2002 11:47:53

A full list of error codes can be found at or in the XPInstall API Reference at

Though XPInstall is enabled by default, there is preference to turn it on and off in the user profile preferences file (prefs.js). To disable XPInstall, set the preference like this:

user_pref("xpinstall.enabled", false);

And be aware that target installation platforms may have this preference turned off, which prevents you from installing any new software in Mozilla.

6.3.3. XPInstall

XPInstall is a technology used for cross-platform installation. Mozilla uses it extensively to install new packages, but as a general-purpose technology, it can be used to install anything on your computer. The XPI file format we described in the section Section 6.3.1 earlier in this chapter is the basic unit of exchange in an XPInstall and the installation script manages the installation.

Installation scripts -- whether they appear within the XPI, on a web page as an external “trigger script,” or elsewhere in JavaScript -- use the XPInstall API to do all the heavy lifting. The XPInstall API includes installation functions (Example 6-16) organized into such high-level objects as the Install object, the InstallTrigger object, and the File object, which you can use to install new Mozilla packages.

Example 6-16. Common XPInstall functions
initInstall( )      // initializes every installation
getFolder( )        // creates a new folder on the target system
addFile( )          // adds files and directories to the install
performInstall( )   // executes the installation
cancelInstall( )    // cancels installation if there are errors

In addition to the XPInstall API installation functions, installation scripts often call methods on the chrome registry itself. As described earlier in this chapter in the Section 6.2.4 section, the chrome registry handles the registration of new files and packages on the local system, the maintenance of user configurable data (such as what skin or theme you currently selected), and several utility functions used to make installations easier and more successful. The Install object

The Install object is the main object in the XPInstall API. It provides most of the methods and properties used in installation scripts.

initInstall(displayName, name, version, flags)

The initInstall( ) method that initializes the installation process takes the following parameters: displayName is the name you give to the installation itself; name is the name of the package to be installed (which must match the name given to the package in the manifests); version is the version of the package being installed (also specified in the manifest); and flags is an optional parameter reserved for future use (which is set to “0” by default and about which you don't have to worry).

Example: initInstall("Example Installation", "xfly", "0.9", 0);

The addFile( ) method adds a single file to the initialized installation. file is a pointer to the file in the XPI that will be installed.

Example: addFile("simple.exe");
err = performInstall( )

The performInstall( ) method starts the installation that you set up.

Example: performInstall( );

The Install object exposes the methods listed in Table 6-1.

Table 6-1. Install object methods

Method Description
AddDirectory Unpacks an entire subdirectory.
AddFile Unpacks a single file.
Alert Displays an Alert dialog box with a message and an OK button.
CancelInstall Aborts the installation of the software.
Confirm Displays a Confirm dialog box with the specified message and OK and Cancel buttons.
deleteRegisteredFile Deletes the specified file and its entry in the Client Version Registry.
Execute Extracts a file from the XPI file to a temporary location and schedules it for later execution.
Gestalt Retrieves information about the operating environment (Mac OS only).
GetComponentFolder Returns an object representing the directory in which a component is installed.
GetFolder Returns an object representing a directory, for use with the addFile method.
GetLastError Returns the most recent nonzero error code.
getWinProfile Constructs an object for working with a Windows .ini file.
getWinRegistry Constructs an object for working with the Windows registry.
InitInstall Initializes installation for the given software and version.
LoadResources Returns an object whose properties are localized strings loaded from the specified property file.
LogComment Adds a comment line to the install log.
Patch Applies a set of differences between two versions.
PerformInstall Finalizes the installation of software.
RegisterChrome Registers chrome with the chrome registry.
ResetError Resets a saved error code to zero.
setPackageFolder Sets the default package folder that is saved with the root node. The InstallTrigger object

When you have very simple installations -- such as when you want to install a new skin -- you may not need to use the services from the Install object. Besides providing the services necessary for "triggering" the downloading of a package from a web site, the InstallTrigger object offers some simple methods for installing when you do not need to rearrange of the disk, register complications, or do other install-type preparation (see Table 6-2).

Table 6-2. InstallTrigger interface showing the role of the InstallTrigger object in the overall installation process

Method Description
compareVersion Compares the version of a file or package with the version of an existing file or package.
Enabled Indicates whether the Software Installation is enabled for this client machine.
getVersionInfo Returns an InstallVersion object representing the version number from the Client Version Registry for the specified software or component.
Install Installs one or more XPI files on the local machine.
installChrome Installs new skin or locale packages in Netscape 6 and Mozilla.
startSoftwareUpdate Initiates the download and installation of specified software. Note: deprecated in favor of install.

This web page installation script defines its own install method in which a callback parameter on the InstallTrigger's own install( ) method checks the success of the installation and displays a relevant alert for the user (as shown in Example 6-17).

Example 6-17. Install script callback
function doneFn (name, result)
   if (result != 0 && result != 999)
     alert("The install didn't seem to work, you could maybe try " +
           "a manual install instead.\nFailure code was " + result + ".");
     alert("Installation complete, please restart your browser.");
function install(packageName, fileName)
   var xpi = new Object( );
   xpi[packageName] = fileName;
   InstallTrigger.install(xpi, doneFn);
<a href="javascript:install('xFly','xfly.xpi');">install</a> Installing non-Mozilla software

The XPInstall technology downloads and installs any software on any machine using Mozilla or Netscape 6/7. The same Install object methods that download, register, and install new Mozilla packages (e.g., new themes or new Mozilla applications like xFly) can be used to download other executables and software into any location on the local machine.

As with Mozilla application installs, you use an installation script within a XPI to initialize the installation, add the files you want to the installation, and then perform the install and put the software in the designated locations. Note that non-Mozilla software installations do not include a registration step, since the chrome registry does not track non-Mozilla software or any more general additions to the operating system. Example 6-18 shows a simple and typical non-Mozilla installation.

Example 6-18. Non-Mozilla software installation script
var xpiSrc = "file.txt";
  "Adding A File",
f = getFolder("Program"); // keyword for the main program
                          // directory on the target platform
                          // (e.g., the "Program Files" dir on win32)
if (0 == getLastError( ))
performInstall( );
    cancelInstall( );

Refer to the “XPInstall API Reference” on for more detailed information about the XPInstall API and how it can be used in more complex installations.

6.3.4. Uninstalling Applications

You may have noticed an uninstall( ) method on the Install object in the XPInstall API. This method does some of the work you need to do to uninstall packages from Mozilla, but it's a buggy process and doesn't finish the job.[1] Beyond the physical removal of the package resources during the uninstall, several RDF files in the chrome registry need to be updated, and the XPInstall uninstall( ) does not get to some of these files.

Fortunately, the JSLib JavaScript developer's library has a well-implemented uninstall function, which you can use by importing the uninstall.js file and calling uninstall on the package you want uninstalled. uninstall.js is one of the JS file collections that comprise the JSLib.

Once you install JSLib, using the uninstall method is simple:

var p = new Uninstall('myPackageName');
p.removePkg( );

You might want to put this uninstall routine in a function so you can reuse it.

function unInstall(pkg) {
   var p = new Uninstall(pkg);
   p.removePkg( );

This method removes the resources themselves and deletes all references to the package in the chrome registry. The pkg parameter is the name of the package as defined in the manifest for that package. The xFly package manifest, for example, defines “xfly” as the name of the package, as shown in Example 6-19.

Example 6-19. Package metadata in the xFly manifest
<!-- xFly package information -->
  <RDF:Description about="urn:mozilla:package:xfly"

Example 6-9 comes from the content package manifest for xFly, which is similar to the full content manifest for the XMLTerm application you saw in Example 6-4.

To uninstall the xFly package, then -- as you should do to the working version you have as you develop before installing the final version -- hook up a menuitem to call the uninstall routine:

<menuitem id="uninstall-item" label="Uninstall xFly" oncommand="unInstall("xfly")" />

This menuitem should have access to a JavaScript file and contains the following code:

function unInstall(pkg) {
   var p = new Uninstall(pkg);
   p.removePkg( );


6.4. Finishing Things Up

We dealt with the xFly example earlier in this chapter and then discussed general information about file formats, installation scripts, and xpinstall. You now have everything you need to make the xFly package an installable application. Borrowing liberally from the examples in the earlier sections Section 6.3.1 and Section 6.3.2, you can bundle a JAR file or the entire subdirectory structure you already created for xFly in the chrome directory:

    xfly      content

Bundle the JAR file into a ZIP file, add an installation script to that ZIP file (and a web trigger script to the application's web page), and make your application available to Mozilla users everywhere.

6.4.1. Creating the xFly XPI

An XPI file is nothing more than a ZIP file with its own installation script. Using a ZIP utility, you can archive the xfly directory and preserve the subdirectory structure so it's installed in the user's chrome directory as it is in your own. Make sure that the ZIP file, whatever it's called, contains the top-level xfly subdirectory as part of this structure. If it is a JAR file you are distributing for your package, make the JAR file (xfly.jar) the top level, with the content, skin, and locale directories contained within:


The URLs you used to refer to various parts of your xFly application (e.g., chrome://xfly/content/xfly.js as part of the command that imports the external script file into the main XUL file) will be registered during the installation process with that xfly directory or JAR file directly underneath the Mozilla chrome directory.

6.4.2. Adding the Installation Script

Once you understand the Section 6.3.2 section (earlier in this chapter), creating an installation script for the xFly application is straightforward, as Example 6-20 shows. In this case, we bundled all the xFly subdirectories in a single JAR file, xfly.jar.

Example 6-20. xFly installation script
const X_MSG             = "Install xFly";
const X_NAME            = "xFly";
const X_VER             = "0.0.1";
const X_JAR_FILE        = "xfly.jar";
const X_CONTENT         = "content/";
const X_SKIN            = "skin/";
const X_LOCALE          = "locale/en-US/";
const X_CHROME          = "chrome";
var err = initInstall(X_MSG, X_NAME, X_VER);
logComment("initInstall: " + err);
logComment( "Installation started ..." );
addFile("We're on our way ...", X_JAR_FILE, getFolder(X_CHROME), "");
err = getLastError( );
if ( err == SUCCESS )  {      // if there have been no errors:
  performInstall( );           // install "xfly.jar"
  alert("Please restart Mozilla");
else  {                       // otherwise
  cancelInstall( );            // cancel the installation.

Save the installation code in Example 6-20 as install.js and add it to the ZIP file you created out of the xfly subdirectory. Name this zip file xfly.xpi. The installation script should be archived at the top level of the XPI file and appear next to the xfly subdirectory or JAR file. Another feature of this script is the declaration of constant variables at the top, for various values used in the script. This feature is good for re-use and organizing your script.

6.4.3. Web Page Installer

The XPI file you created in the last two sections, with its internal install.js file, is all you need to make your Mozilla application portable and installable. The final step creates a link on a regular web page that tells Mozilla where this file is, as shown in Example 6-21.

Example 6-21. Web page trigger
<a href="#"
   {'xfly' :
   Install my cool xFly Application</a>

When the user browses the application web page and clicks the “Install my cool xFly Application” link shown above, Mozilla finds and downloads xfly.xpi in the same directory. It then opens the archive, reads the install script, creates the xfly subdirectory on the local machine or moves the JAR file onto the local machine, and registers it with the chrome registry. When the user restarts the browser, the xFly application is integrated into Mozilla and ready for use. The user can access it with any overlays that put it into the browser's interface (e.g., as an item in the Tools menu) or invoke it directly by using the special chrome option for pointing to a registered chrome:

mozilla -chrome chrome://xfly/content

You don't need to have an install page to install a XPI in Mozilla. If, instead of a web page, you provide a URL that points directly to a XPI, Mozilla displays a dialog that asks the user whether they want to initiate the installation of that XPI. As with any new software installation, however, a page that describes the package and what it does can help allay fears and promote use.

6.5. Extra Tricks for Customizing an Application

If the Mozilla application you are working on is more autonomous than a package that sits up on a Mozilla installation, you may want to add extra customization. Here are two common features: the program icon and the splash screen. Some features require that you build the source code yourself, even just a particular module instead of the whole tree. Refer to Appendix A for more details on obtaining and building the source code.

6.5.1. Icons

Program icons are important for several reasons. Primarily, however, they are a visual representation of your application on the system that it runs on, whether it runs in a file explorer, a taskbar, or an application selector. This section tells you where to locate the current icons in the Mozilla application and what files or resources need to be changed to make your icon the default for Mozilla. Windows

In Windows, create your own icon and then follow these steps:

  1. Go to the mozilla/xpfe/bootstrap folder in the source tree.
  2. Open the splash.rc resource file. This can be done in the text editor of your choice or in any program with special handling for Windows resource files.
  3. Change the icon resource to the file of your choice.
// Program icon.
  1. Recompile the bootstrap module. This recompilation regenerates the mozilla.exe executable file.
C:\mozilla\src>cd mozilla\xpfe\bootstrap
C:\mozilla\src\mozilla\xpfe\bootstrap>nmake -f

An alternative to Steps 2 and 3 is to give your icon the same name as the Mozilla icon (mozilla.ico) and just drop it into the tree, replacing the existing one shown in Figure 6-6.

Figure 6-6. Windows taskbar with Mozilla icon

images Unix

X Windows uses the common X Pixmap (XPM) format for icons. XPM files are C source code files, with each pixmap defined as a static character array. The window manager expects to find two XPM files for each icon specified in the configuration files as ICON. Mozilla has two files for icons located in mozilla/src/gtk: mozicon16.xpm and mozicon50.xpm. Many utilities, such as the GIMP, PaintShopPro, and Xview, can transform images from other common formats. Macintosh

The Macintosh BNDL resource (OS icons for files and applications) and related resource types (4bit, 8bit, large, small icons, masks, and FREF) are contained in nsMacBundle.rsrc, located at mozilla/xpfe/bootstrap. It also contains a MOZZ resource that references the Mozilla software license. All Macintosh software have this set of resources.

If you want to change icons on a window-by-window basis, do it only in Mozilla on the Windows platform. In the chrome root, there exists a directory \icons\default\. Within this directory, you can place any number of icons for windows in your application. The filename has to be the same as the XUL window ID: <window_id>.ico. One example of an icon being used in this way is the DOM Inspector window in Mozilla. In the \icons\default\ directory you will find the file winInspectorMain.ico on Windows. This option is good for package authors who add windows to the Mozilla application and do not want to hijack this resource completely. Icons can be installed as part of an XPI.

6.5.2. Splash Screen

Are splash screens a necessary startup feature for a program or a shameless plug? The answer is probably somewhere in between, leaning toward the necessary in the case of Mozilla (Figure 6-7 shows Mozilla's splash screen).

Figure 6-7. Mozilla's splash screen


Because Mozilla is a large application and needs to process so much (including profiles, initialization code, and theme/locale selection from the chrome registry) before you actually see the first window appear, users need a visual clue that something is happening when Mozilla starts up.

If your application also requires a lot of processing at startup or if you would like to customize your application, then creating and using your own unique splash screen is essential. Windows

The splash screen file is a bitmap image that also lives in the same splash.rc file that houses the icon file, perhaps more appropriately named in this case.

// Splash screen bitmap.

Again, you have the option of changing the resource file or calling the image file the same name as the Mozilla splash (splash.bmp) and dropping it into the tree. Both of options require recompilation of the bootstrap module. Unix

The splash screen uses the same XPM format as is used for the icons. The file is called splash.xpm and is located in mozilla/xpfe/bootstrap. Note that the splash display is turned off by default on this platform and can be displayed by using the -splash switch in a command shell.

/mozilla -splash Macintosh

The file Splash.rsrc (located in the source tree at mozilla/xpfe/bootstrap) contains Macintosh resources to display the splash screen (native DLOG, DITL, PICT) during startup while the shared libraries are loaded and before the profile manager is shown.

[1] Currently, some open bugs in Bugzilla are tracking the progress of this method and its improvement.

Get Creating Applications with Mozilla now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.