Mozilla teams recently wrote tons of new API in a very short period of time, mostly for Firefox OS, but not only. As Firefox Desktop, Firefox Mobile and Firefox OS are based on the same source code, some of these API can easily be enabled on Desktop and mobile.
The aim of this article is to write down a simple API example from ground and try to explain all necessary things you need to know before writing an API with the same level of expertise than what did Firefox OS engineers.
The example API: « CommonJS require »
Let’s say we would like to expose to websites a
require() method that act like
the nodejs/commonjs method with the same name. This function allows you to load
Any webpage will be able to use its
hello function like this:
Liquid error: undefined method `join’ for #<String:0x00000002647e98>
Simpliest implementation possible
In this first example I stripped various advanced features in order to ease
jumping into Firefox internal code. I bundled this example as a Firefox addon
so that you can easily see it running and also hack it.
You can download it here. Once installed, you will have to relaunch Firefox,
open any webpage, then open a Web console and finally execute the
navigator.webapi.require code I just gave.
Now let’s see what’s inside. This .xpi file is just a zip file so you can open it and see three files:
A really boring file describing our addon. The only two important
fields in this file are:
<em:unpack>true</em:unpack> required when you need to register a XPCOM file.
More info here.
1 2 3 4 5 6 7 8 9 10
Liquid error: undefined method `join’ for #<String:0x00000002646de0>
I let you discover the implementation of the
require method, but it will
be your job to implement such method. Now, you have the very minimal set where
you can tweak the returned value of the
init method and expose your own
API to webpages.
Now note that this is a very minimal example. I’ll try to continue blogging about that and eventually talk about:
- interfaces definition,
- custom event implementation,
- other XPCOM categories (in order to inject on other object than navigator),
- how to implement a cross process API (mandatory for Firefox OS),
- prototyping via the Addon SDK,