How to Build an XPCOM Component in Javascript

공헌자 숫자: 2명

본 문서는 자바스크립트에서 XPCOM 컴포넌트를 만드는 방법을 소개합니다. 이 문서에서는 XPCOM이 어떻게 움직이는지 혹은 그에 대한 코드는 다루지 않습니다. 자세한 사항은 XPCOM에서 아실 수 있습니다. 여기서는 실제로 이를 어떻게 움직이게하는 가에 달려 있습니다.


구현 방법

아래 예제는 "Hello World!"라는 메시지를 표시하는 간단한 방법입니다. This example component will expose a single method, which returns the string "Hello World!".

인터페이스 재정의

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.

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 <tt>windows\bin\x86</tt> within the zip into the <tt>bin</tt> 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, <tt>{sdk_dir}</tt> 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.

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

Installation

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

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

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

Other resources

문서 태그 및 공헌자

Contributors to this page: Channy, Yookh80
최종 변경: Channy,