Wednesday, September 25, 2013

Firefox modules - Implementing a module, specifically, ContentPolicy

In Firefox, Modules are isolated global environments. Imagine the bastard child of a WebWorker and a CommonJS/AMD import/require statements (seehttp://addyosmani.com/writing-modular-js/).
As stated, Module are global (singleton) for the Firefox application, and are started (run) the first time they are imported into another (running) JS scope. Modules can be registered with Firefox when they start up.
In this example, we'll implement a nsIContentPolicy module, which can be used for intercepting (and blocking) ALL requests made from the browser.

To get started:

1) Create a chrome/modules folder. Create the module file, $(module_name).jsm, where module_name can be what you like.
2) Add to the chrome.manifest, where app_name is the same name used in the manifest already:  "resource    $(app_name)    chrome/modules/"
3) Add this code to where ever you want the module to be accessible from, where scope_reference is where ever you want the exported module objects to be exposed on: "Components.utils.import("resource://$(app_name)/$(module_name).jsm", $(scope_reference));"
4) Inside $(module_name).jsm, you'll need this basic skeleton code. Since the example module will implement nsIContentPolicy, I'll use the name "ContentPolicy":



Note: You must customize the  "classDescription", "classID", "contractID", and QueryInterface list. But, the QueryInterface list must include "Components.interfaces.nsIFactory"
5) Actually add and implement all the methods which you declare that you will implement (in QueryInterface list of Interfaces).
6) EXPORTED_SYMBOLS string array will add all objects on the module's scope (window) into the $(scope_reference) passed into the import call.


Registering the Module with Firefox - If you want FF to USE YOUR MODULE, then you have to REGISTER IT

For registering with Firefox, and for ContentPolicy in particular, we need to add the Module as a listener for certain events. SEE THIRD SNIPPET

Custom for nsIContentPolicy 

Must add these methods to implement nsIContentPolicy: SEE SECOND SNIPPET

No comments:

Post a Comment