Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Compiler un composant XPCOM javascript

 

Note: Page en cours de traduction

Ceci est un tutoriel "Hello World" de création de composant XPCOM javascript. Il ne décrit pas comment ni pourquoi les XPCOMs ou chaque bit de ce code fonctionnent de cette manière. Cela a déjà été fait ailleurs (en). En revanche, est décrite, ici, la façon de faire marcher un composant en un minimum d'étapes, les plus simples possibles. 

Implementation

Cet exemple de composant fournit une seule méthode retournant la chaine "Hello World!".

Définition de l'Interface

Si vous voulez utiliser votre composant dans des XPCOMs tiers, vous devez définir les interfaces que vous voulez fournir. Si vous voulez vous en servir uniquement depuis JavaScript, vous pouvez passer à la section suivante.

Il existe de beaucoup d'interfaces déjà définies dans les applications Mozilla, il est donc probable qu'une nouvelle soit inutile. Vous pouvez parcourir les interfaces XPCOMs existantes à différents endroits dans les sources de Mozilla, ou avec XPCOMViewer, un navigateur d'interfaces et composants. Une ancienne version est disponible pour Firefox sur les miroirs mozdev.

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.

Compilation de la Typelib

La définition de votre interface doit être compilée en format binaire (XPT) pour être prise en compte et exploitable dans les applications Mozilla. Cette compilation peut se faire avec le SDK Gecko. Vous en trouverez les versions Linux, Mac et Windows en lisant l'article Gecko SDK (en).

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.

Exécutez cette commande pour compiler la typelib. Ici, {sdk_dir} est le dossier dans lequel vous avez décompressé le SDK Gecko.

{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.

Ceci créera le fichier typelib HelloWorld.xpt dans le dossier de travail courant (Le drapeau -I est un i majuscule et non un L minuscule).

Création du Composant

HelloWorld.js

/***********************************************************
constantes
***********************************************************/

// 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: https://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() {
// If you only need to access your component from Javascript, uncomment the following line:
//this.wrappedJSObject = this;
}

// 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; }

Utilisation de XPCOMUtils

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() {
// If you only need to access your component from Javascript, uncomment the following line:
//this.wrappedJSObject = this;
}

// 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 (remove argument if skipped steps above)
  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);
}
Note: NSGetModule is depreciated since Gecko 2.0 and is replaced by NSGetFactory. See XPCOM_changes_in_Gecko_2.0 for more details.


Installation

Pour les extensions:

  1. Copy HelloWorld.js, and HelloWorld.xpt (only if you defined and compiled the IDL) to {extensiondir}/components/
  2. Delete compreg.dat and xpti.dat from your profile directory.
  3. Restart application.

Pour Firefox:

  1. Copy HelloWorld.js, and HelloWorld.xpt (only if you defined and compiled the IDL) 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.

Utilisation de votre Composant

Avec wrappedJSObject

If you only intend to access your component from Javascript, i.e. you skipped the sections "Defining the Interface" and "Compiling the Typelib" above, you uncommented the "wrappedJSObject" line in the class constructor, and you removed the "[Components.interfaces.nsIHelloWorld]" argument for the call to XPCOMUtils.generateQI() in QueryInterface, then you can access your component like this:

try {
        var myComponent = Components.classes['@dietrich.ganx4.com/helloworld;1']
                                    .getService().wrappedJSObject;

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

For more information about wrappedJSObject, see here.

Avec instantiation du XPCOM

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

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

Autres resources

Étiquettes et contributeurs liés au document

 Contributeurs à cette page : Demos
 Dernière mise à jour par : Demos,