javascriptfirefoxxpcom

Expose an XPCOM component to javascript in a web page


I'd like to write a XPCOM component that gets exposed as a javascript object in a web page. Something like Google Gears is what I'm seeking. That is, after installing the Google Gears Firefox extension, the javascript object 'google.gears' is available to any web page that wants to use it. I've found lots of mozilla documentation on XPCOM development, but nothing on exposing the component to javascript running in a web page. Is this possible with XPCOM? Do I need to write a Firefox plug-in instead of an extension?


Solution

  • I'm doing exactly that with a new API in Firefox 4 - nsiDOMGlobalPropertyInitializer - which lets you create a JS object to attach to all windows lazily. This is the way the new Web Console in Firefox 4 is created.

    You have to have the following QI property in your component:

    QueryInterface: XPCOMUtils.generateQI([Ci.nsIDOMGlobalPropertyInitializer]),
    

    Here is an example of a full implementation in an extension:

    https://github.com/daviddahl/domcrypt/blob/master/extension/domcrypt/components/domcrypt.js

    SO basically, QI to Ci.nsIDOMGlobalPropertyInitializer, then make sure your manifest has a line like:

    category JavaScript-global-property crypt @droplettr.com/domcrypt;1
    

    see: https://github.com/daviddahl/domcrypt/blob/master/extension/domcrypt/components/domcrypt.manifest