Code snippets:JS XPCOM
From MDC
Here are a few useful snippets of code for dealing with XPCOM components in JavaScript.
Contents |
[edit] Contract IDs
A contract ID is a unique name for an XPCOM object. They are used to create or access well-known objects in XPCOM.
[edit] Interfaces
Every XPCOM object implements one or more interfaces. An interface is simply a list of constants and methods that can be called on the object, an example is nsIFile. Every XPCOM object must implement the nsISupports interface.
[edit] Accessing XPCOM components from JavaScript
XPCOM objects are either created as new instances (each creation gives you a completely new COM object) or as services (each access gives you the same COM object, often called a singleton). Whether you must create a new instance or access as a service depends on the contract. In order to get an XPCOM object you need to know the contract ID of the object and the interface that you wish to use on it.
[edit] Creating an instance of a component
var component = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsIFile);
This creates a new instance of the object with contract ID @mozilla.org/file/local;1 and allows you to call methods from the nsIFile interface on it.
[edit] Getting an XPCOM service
var preferences = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService);
You can then call any methods in the nsIPrefService interface on the preferences object.
[edit] Getting a different interface for a component
Some components implement more than one interface. Sometimes JavaScript is clever enough to know all the interfaces available on a component, but in most cases you will have to explicitly check for an interface. With the preferences service from the previous example we can do the following:
preferences = preferences.QueryInterface(Components.interfaces.nsIPrefBranch2);
This allows you to use the methods in the nsIPrefBranch2 interface.
[edit] Determining which interfaces an XPCOM component supports
To display a list of all interfaces that an XPCOM component supports, do the following:
// |c| is the XPCOM component instance
for each (i in Components.interfaces) { if (c instanceof i) { alert(i); } }
In this context, instanceof is the same as QueryInterface except that it returns false instead of throwing an exception when |c| doesn't support interface |i|. Another difference is that QueryInterface returns an object, where as instanceof returns a boolean.
[edit] Implementing XPCOM components in JavaScript
Here is a simple stub of a JavaScript XPCOM component. In order to use it you must do the following:
- Replace the 3 strings at the top of the initModule with your own.
- Change the test in the QueryInterface method to work for any interfaces you are implementing.
- Add methods to the prototype that appear in the interfaces you are implementing.
- Add any initialisation code you want into the ExampleComponent constructor.
function ExampleComponent()
{
// Add any initialisation for your component here.
}
ExampleComponent.prototype = {
QueryInterface: function(iid)
{
if (iid.equals(Components.interfaces.myInterface)
|| iid.equals(Ci.nsISupports))
{
return this;
}
throw Components.results.NS_ERROR_NO_INTERFACE;
}
};
var initModule =
{
ServiceCID: Components.ID("{examplee-xamp-leex-ampl-eexampleexam}"), // Insert a guid in the quotes
ServiceContractID: "@example.com/example;1", // Insert a contract ID in the quotes
ServiceName: "", // Insert your own name in the quotes
registerSelf: function (compMgr, fileSpec, location, type)
{
compMgr = compMgr.QueryInterface(Ci.nsIComponentRegistrar);
compMgr.registerFactoryLocation(this.ServiceCID,this.ServiceName,this.ServiceContractID,
fileSpec,location,type);
},
unregisterSelf: function (compMgr, fileSpec, location)
{
compMgr = compMgr.QueryInterface(Ci.nsIComponentRegistrar);
compMgr.unregisterFactoryLocation(this.ServiceCID,fileSpec);
},
getClassObject: function (compMgr, cid, iid)
{
if (!cid.equals(this.ServiceCID))
throw Components.results.NS_ERROR_NO_INTERFACE
if (!iid.equals(Components.interfaces.nsIFactory))
throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
return this.instanceFactory;
},
canUnload: function(compMgr)
{
return true;
},
instanceFactory:
{
createInstance: function (outer, iid)
{
if (outer != null)
throw Components.results.NS_ERROR_NO_AGGREGATION;
return new ExampleComponent().QueryInterface(iid);
}
}
}; //Module
function NSGetModule(compMgr, fileSpec)
{
return initModule;
}
[edit] XPCOMUtils - About protocol handler
New in Firefox 3This example implements a quick about protocol handler in JS using XPCOMUtils.jsm.
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
const Cc = Components.classes;
const Ci = Components.interfaces;
function MyAboutHandler() { }
MyAboutHandler.prototype = {
newChannel : function(aURI) {
if(!aURI.spec == "about:mystuff") return;
var ios = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
var channel = ios.newChannel("chrome://mystuff/content/mystuff.xul", null, null);
channel.originalURI = aURI;
return channel;
},
getURIFlags: function(aURI) {
return Ci.nsIAboutModule.URI_SAFE_FOR_UNTRUSTED_CONTENT;
},
classDescription: "About MyStuff Page",
classID: Components.ID("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"),
contractID: "@mozilla.org/network/protocol/about;1?what=mystuff",
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
}
function NSGetModule(aCompMgr, aFileSpec) {
return XPCOMUtils.generateModule([MyAboutHandler]);
}
[edit] Utility for Instance/Service creation
The following code should work for most if not all classes and interfaces in XPCOM. It removes a little bit of the redundant (and unattractive) information needed when creating an XPCOM instance or service.
// Can forego ";1" in middle or at the end of a passed in class name, but not ";2" (for the few cases that there are of the latter)
function xpcServ(classArg, intf) {
var clss = '@mozilla.org/'+classArg.replace(/^@mozilla\.org\//, '');
clss = clss.replace(/;1\?/, '?').replace(/([^;][^\d])\?/, '$1;1?').replace(/;1$/, '');
if (!clss.match(/;\d/)) {
clss += ';1';
}
var int = 'nsI'+intf.replace(/^nsI/, '');
return Components.classes[clss].getService(Components.interfaces[int]);
}
function xpcInst(classArg, intf) {
var clss = '@mozilla.org/'+classArg.replace(/^@mozilla\.org\//, '');
clss = clss.replace(/;1\?/, '?').replace(/([^;][^\d])\?/, '$1;1?').replace(/;1$/, '');
if (!clss.match(/;\d/)) {
clss += ';1';
}
var int = 'nsI'+intf.replace(/^nsI/, '');
return Components.classes[clss].createInstance(Components.interfaces[int]);
}
var cs = xpcServ('consoleservice', 'ConsoleService'); // Class: @mozilla.org/consoleservice;1 and Interface: nsIConsoleService
cs.logStringMessage('testing console');
var pls = xpcInst('pref-localizedstring', 'PrefLocalizedString');
// Do something with a localized string instance
// Can avoid ';1' in class name before '?'
var pcast = xpcInst('network/protocol?name=pcast', 'ProtocolHandler');
// But can't avoid ';2' in class name before '?'
var sock = xpcInst('network/socket;2?type=socks', 'SocketProvider');