From time to time when reviewing add-ons on AMO, I notice that the version number of the extension is hard-coded. The author needs it to fork some code because of API differences across versions of the Mozilla application, or perhaps some other reason.
Hard-coding is not necessary. In most cases the version should only be in install.rdf. The version can be retrieved from the nsIExtensionManager/nsIUpdateItem interfaces. Here’s the basic snippet:
var emid = "cooladdon@mydomain.com"; // Should correspond to em:id in install.rdf
var version = MyExt.getExtensionVersion(emid);
MyExt.getExtensionVersion = function(emid)
{
var em = Components.classes["@mozilla.org/extensions/manager;1"]
.getService(Components.interfaces.nsIExtensionManager);
var addon = em.getItemForID(emid);
var versionString = addon.version;
return versionString;
}
And so it goes. You can retrieve other information about the extension via these interfaces.











May I suggest you create an article on devmo with that?
It is worth pointing out that there are still good reasons why hardcoding can be the better option, particularly if you have some automated build system that can take care of updating your version everywhere for you.
The problem is one of performance. In normal running the extensions database isn’t loaded until absolutely necessary, the first script to call getItemForID will however force it to load. This costs some 20ms on a fairly fast machine with just 5 add-ons installed. It is something to be wary of if your version check runs during startup.
Daniel, this is already on MDC, though I grant you it could probably do with being somewhere better:
https://developer.mozilla.org/en/Code_snippets/Miscellaneous#Retrieving_the_version_of_an_extension_as_specified_in_the_extension%27s_install.rdf
Seems like you missed install.rdf in the ems?
Using FUEL Extensions would make the code easier still, I think.
Unfortunately, things aren’t as easy if you have to support SeaMonkey 1.1 (or K-Meleon, for that reason). There is a way to retrieve extension version there as well but it is too unreliable so I decided to hardcode. The version number is filled in by my build scripts everywhere anyway so it doesn’t matter.
FUEL support something like this too.
Application.extensions.get(“myext@foo.com”).version
Of course that’s Firefox only and won’t work in older versions I guess?
It may also be important to note that, just like all the three million other interfaces in Mozilla, nsIExtensionManager isn’t frozen. Or maybe it isn’t important; it’s up to the extension developer to decide :)