This solution was written for JPM 1.0.0.
It is also a proof-of-concept, and has not been thoroughly tested yet. Use at your own risk!
The Firefox module loader, by default, has all modules live in their own isolated world and don't share any global object. You can't monkey-patch default methods/the global object in one module of your extension, and have it be affected in another module of your extension.
Mozilla's JPM tool handily lets you use packages straight from NPM in your Firefox add-on, but the globals in the JS environment in an extension's main process are pretty barebones until you require
anything. Globals that tons of NPM modules take for granted as being available - like setTimeout
, XMLHttpRequest
, even variables pointing to the global object like global
or window
arent there.
And because of the sandboxing feature mentioned above, you can't monkey-patch your environment to be compatible with a module if you wanted to.
The loader system does, however, have an undocumented option called sharedGlobal
which makes your modules all share the same globals. To take advantage of this, you'll need to start up a custom loader and then run your extension's main process through this custom loader.
In this gist, I have a file called _loader.js
which was ripped from sdk/addon/bootstrap.js
and patched to work as a stand-alone module in a Firefox addon. It acts as the entry point into this example extension, then starts up another loader system using index.js
as its entry point
To make it use a file other than index.js
as the entry point, edit the line that's changing metadata.main
to a file of your choosing.
Important: This also results in SDK modules you require()
sharing globals with your addon, and they were not written with this behavior in mind. Thankfully, you can maintain a blacklist (sharedGlobalBlacklist
) of modules that you don't want to share globals with. Notably, method/core
will not work at all and will stop your extension from starting altogether if you don't put it in this blacklist.
If you'd like to use the NPM Pouch DB in your Firefox addon, this blog post has figured out what you need to monkey-patch in to get it working right:
http://siphon9.net/loune/2015/02/pouchdb-for-firefox-addon-sdk/