DOM and JavaScript interoperability
Deprecation noticeCheerpJ 2 is deprecated. Consider migrating to CheerpJ 3 .
CheerpJ allows users to interact with the browser DOM directly from Java, without overhead. To achieve this you will need to use the CheerpJ Java API (cheerpj-dom.jar
) and found at the CheerpJ downloadable archive. Usage examples are shown below.
Basic example
Using Strings
Itβs important to keep in mind that Java Strings are not JavaScript Strings. To avoid confusion, in CheerpJ the JSString
name is used for the JS version. The static Global.JSString
utility function can be used to create JSString
s from Java String
s. If a JSString
needs to be used many times it could be useful to cache it. Similarly the Global.JavaString
function can be used to convert back from JSString
to normal Java String
. See Global.JSString and Global.JavaString.
Calling JS methods
The Global
class provides a few static methods that can be used to call arbitrary JS functions in the global scope, See Global.jsCall
The various methods behave the same, with the only difference being the expected return type. As JavaScript functions are untyped CheerpJ does not have enough information to auto-box the returned values, so you need to use the right return type on the call site. Java Strings parameters will be automatically converted to JavaScript Strings.
Building the code
Assuming the example above is contained in DomExample.java
, you need to first build the program using the standard javac
compiler, create a JAR and then create the JAR.JS from it using CheerpJ. In both steps the cheerpj-dom.jar
must be explicitly added to the command line as a dependency.
Further reading
- Java API (Reference)