Visit Mozilla.org

How to Build an XPCOM Component in Javascript

From MDC


This is a "Hello World" tutorial for creating an XPCOM component in JavaScript. This tutorial does not describe how and why XPCOM works the way it does, or what every bit of the example code does. That's been detailed elsewhere. This tutorial will show you what you need to do to get a component working in as few and as simple steps as possible.

Caveat: This was done on a Mac. YMMV with Windows.

Contents


[edit] Implementation

This example component will expose a single method, which returns the string "Hello World!".

[edit] Defining the Interface

If you want to use your component from JavaScript, or in other XPCOM components, you must define the interfaces that you want exposed (if you want to use your component only from JavaScript, you can use the wrappedJSObject trick so that you don't need to generate an interface as described here).

There are many interfaces already defined in Mozilla applications, so you may not need to define a new one. You can browse existing XPCOM interfaces at various locations in the Mozilla source code, or using XPCOMViewer, a GUI for browsing registered interfaces and components. You can download an old version of XPCOMViewer that works with Firefox 1.5 from mozdev mirrors.

If an interface exists that meets your needs, then you do not need to write an IDL, or compile a typelib, and may skip to the next section.

If you don't find a suitable pre-existing interface, then you must define your own. XPCOM uses a dialect of IDL to define interfaces, called XPIDL. Here's the XPIDL definition for our HelloWorld component:

HelloWorld.idl

#include "nsISupports.idl"

[scriptable, uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)]
interface nsIHelloWorld : nsISupports
{
  string hello();
};  

Note that you must generate a new UUID for each XPCOM component that you create. See Generating GUIDs for more information.

[edit] Compiling the Typelib

Your interface definition must be compiled into a binary format (XPT) in order to be registered and used within Mozilla applications. The compilation can be done using the Gecko SDK. You can learn how to get Mac, Linux, and Windows versions of the Gecko SDK by reading the article Gecko SDK.

Note: On Windows if you download the Gecko SDK without the whole build tree, you will be missing some required DLLs for xpidl.exe and it will run with no errors but not do anything. To fix this download the Mozilla build tools for Windows and copy the DLLs from windows\bin\x86 within the zip into the bin directory of the Gecko SDK.
Note: The Mac version of the SDK provided for download is PowerPC-only. If you need an Intel version, you'll need to compile it yourself as described on that page.

Execute this command to compile the typelib. Here, {sdk_dir} is the directory in which you unpacked the Gecko SDK.

{sdk_dir}/bin/xpidl -m typelib -w -v -I {sdk_dir}/idl -e HelloWorld.xpt HelloWorld.idl


Note: On Windows you must use forward slashes for the include path.

(The -I flag is an uppercase i, not a lowercase L.) This will create the typelib file HelloWorld.xpt in the current working directory.

[edit] Creating the Component

HelloWorld.js

/***********************************************************
constants
***********************************************************/

// reference to the interface defined in nsIHelloWorld.idl
const nsIHelloWorld = Components.interfaces.nsIHelloWorld;

// reference to the required base interface that all components must support
const nsISupports = Components.interfaces.nsISupports;

// UUID uniquely identifying our component
// You can get from: http://kruithof.xs4all.nl/uuid/uuidgen here
const CLASS_ID = Components.ID("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx}");

// description
const CLASS_NAME = "My Hello World Javascript XPCOM Component";

// textual unique identifier
const CONTRACT_ID = "@dietrich.ganx4.com/helloworld;1";

/***********************************************************
class definition
***********************************************************/

//class constructor
function HelloWorld() {
};

// class definition
HelloWorld.prototype = {

  // define the function we want to expose in our interface
  hello: function() {
      return "Hello World!";
  },

  QueryInterface: function(aIID)
  {
    if (!aIID.equals(nsIHelloWorld) &&    
        !aIID.equals(nsISupports))
      throw Components.results.NS_ERROR_NO_INTERFACE;
    return this;
  }
};

/***********************************************************
class factory

This object is a member of the global-scope Components.classes.
It is keyed off of the contract ID. Eg:

myHelloWorld = Components.classes["@dietrich.ganx4.com/helloworld;1"].
                          createInstance(Components.interfaces.nsIHelloWorld);

***********************************************************/
var HelloWorldFactory = {
  createInstance: function (aOuter, aIID)
  {
    if (aOuter != null)
      throw Components.results.NS_ERROR_NO_AGGREGATION;
    return (new HelloWorld()).QueryInterface(aIID);
  }
};

/***********************************************************
module definition (xpcom registration)
***********************************************************/
var HelloWorldModule = {
  registerSelf: function(aCompMgr, aFileSpec, aLocation, aType)
  {
    aCompMgr = aCompMgr.
        QueryInterface(Components.interfaces.nsIComponentRegistrar);
    aCompMgr.registerFactoryLocation(CLASS_ID, CLASS_NAME, 
        CONTRACT_ID, aFileSpec, aLocation, aType);
  },

  unregisterSelf: function(aCompMgr, aLocation, aType)
  {
    aCompMgr = aCompMgr.
        QueryInterface(Components.interfaces.nsIComponentRegistrar);
    aCompMgr.unregisterFactoryLocation(CLASS_ID, aLocation);        
  },
  
  getClassObject: function(aCompMgr, aCID, aIID)
  {
    if (!aIID.equals(Components.interfaces.nsIFactory))
      throw Components.results.NS_ERROR_NOT_IMPLEMENTED;

    if (aCID.equals(CLASS_ID))
      return HelloWorldFactory;

    throw Components.results.NS_ERROR_NO_INTERFACE;
  },

  canUnload: function(aCompMgr) { return true; }
};

/***********************************************************
module initialization

When the application registers the component, this function
is called.
***********************************************************/
function NSGetModule(aCompMgr, aFileSpec) { return HelloWorldModule; }

[edit] Using XPCOMUtils

New in Firefox 3 In Firefox 3 and later you can use import XPCOMUtils.jsm using Components.utils.import to simplify the process of writing your component slightly. The imported library contains functions for generating the module, factory, and the NSGetModule and QueryInterface functions for you. Note: it doesn't do the work of creating your interface definition file or the type library for you, so you still have to go through those steps above if they haven't been done. The library provides a simple example of its use in the source code (js/src/xpconnect/loader/XPCOMUtils.jsm), but here's another using this example. To begin, include a line at the top of your interface to import the XPCOMUtils library:

 Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

then implement your interface the same way you did above, except with a few modifications so that XPCOMUtils can set it up properly:

/***********************************************************
class definition
***********************************************************/

//class constructor
function HelloWorld() {
};

// class definition
HelloWorld.prototype = {

  // properties required for XPCOM registration:
  classDescription: "My Hello World Javascript XPCOM Component",
  classID:          Components.ID("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"),
  contractID:       "@dietrich.ganx4.com/helloworld;1",

  // [optional] custom factory (an object implementing nsIFactory). If not
  // provided, the default factory is used, which returns
  // |(new MyComponent()).QueryInterface(iid)| in its createInstance().
  _xpcom_factory: { ... },

  // [optional] an array of categories to register this component in.
  _xpcom_categories: [{

    // Each object in the array specifies the parameters to pass to
    // nsICategoryManager.addCategoryEntry(). 'true' is passed for both
    // aPersist and aReplace params.
    category: "some-category",

    // optional, defaults to the object's classDescription
    entry: "entry name",

    // optional, defaults to the object's contractID (unless 'service' is specified)
    value: "...",

    // optional, defaults to false. When set to true, and only if 'value' is not
    // specified, the concatenation of the string "service," and the object's contractID
    // is passed as aValue parameter of addCategoryEntry.
     service: true
  }],

  // QueryInterface implementation, e.g. using the generateQI helper
  QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIHelloWorld]),

  // ...component implementation...
  // define the function we want to expose in our interface
  hello: function() {
      return "Hello World!";
  },
};

XPCOMUtils does the work of creating the module and factory for you after this. Finally, you create an array of your components to be created:

 var components = [HelloWorld];

and update NSGetModule to use this array and XPCOMUtils:

 function NSGetModule(compMgr, fileSpec) {
   return XPCOMUtils.generateModule(components);
 }

So the total simplified version of your component now looks like (of course documentation and comments aren't a bad thing, but as a template something smaller is nice to have):

Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");

function HelloWorld() { };

HelloWorld.prototype = {
  classDescription: "My Hello World Javascript XPCOM Component",
  classID:          Components.ID("{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}"),
  contractID:       "@dietrich.ganx4.com/helloworld;1",
  QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIHelloWorld]),
  hello: function() { return "Hello World!"; }
}
var components = [HelloWorld];
function NSGetModule(compMgr, fileSpec) {
  return XPCOMUtils.generateModule(components);
}

[edit] Installation

[edit] For extensions:

  1. Copy HelloWorld.js and HelloWorld.xpt to {extensiondir}/components/
  2. Delete compreg.dat and xpti.dat from your profile directory.
  3. Restart application

[edit] For Firefox

  1. Copy HelloWorld.js and HelloWorld.xpt to the {objdir}/dist/bin/components directory, if running from the source.
  2. Delete compreg.dat and xpti.dat from the components directory.
  3. Delete compreg.dat and xpti.dat from your profile directory.
  4. Restart application

[edit] Using Your Component

try {
        // this is needed to generally allow usage of components in javascript
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");

        var myComponent = Components.classes['@dietrich.ganx4.com/helloworld;1']
                                    .createInstance(Components.interfaces.nsIHelloWorld);

        alert(myComponent.hello());
} catch (anError) {
        dump("ERROR: " + anError);
}

[edit] Other resources