Visit Mozilla.org

Java in Firefox Extensions

From MDC

If you are in need of calling Java code from within a Firefox extension, you can make use of LiveConnect. LiveConnect gives your extension's JavaScript code (linked from or contained in XUL code) access to 2 objects: java and Packages. These 2 objects let you make use of the standard JDK classes, e.g.,

var aJavaList = new java.util.LinkedList();

If you want to load your own JARs, then you can create your own Java class loader, e.g.,

var cl = new java.net.URLClassLoader(
    [ new java.net.URL('http://foo.net/bar.jar') ]
);

var aClass = java.lang.Class.forName("org.mozilla.developer.HelloWorld", true, cl);
var aStaticMethod = aClass.getMethod("getGreeting", []);
var greeting = aStaticMethod.invoke(null, []);
alert(greeting);

This technique only works in JavaScript code linked from or contained in XUL files. If you wish to call Java code from within JavaScript code that implements some XPCOM components, at this time, you need a different technique (refer to the Java Firefox Extension). A good reason for calling Java from within an XPCOM component rather than from XUL is to maintain a singleton (some singular Java object) across all Firefox windows. If you call Java from XUL, then each Firefox window will have its own class loader and hence its own "singleton".

The extension XqUSEme borrows some of the code of the above in order to grant full privileges to Java within a Firefox extension, but it is easier to understand and doesn't require creation of a XPCOM component. (See also the Talk page for further potential examples of class instantiations which can also work on JAR files not placed in the /components directory.