Many TeaVM apps are self-contained, mostly calling other Java code or
Web APIs via JSO wrappers. In certain cases, however, you may want to
make a method that can be invoked from JavaScript.
- Expose one method to be called externally
- Build a library to be reused from other JS apps
The main() method
TeaVM by default exposes the main()
method of your main
class (mainClass in your POM configuration) to JavaScript. The
traditional mechanism to invoke the method is this line in your site's index.html:
<body onload="main()">
You can also pass String parameters to your main method.
Adding Methods To main()
konsoletyper posted a tip to expose new methods, reachable via main.
interface Exported extends JSObject {
void foo();
}
public class Main {
public static void main(String[] args) {
exportAPI(new Exported() {
@Override
public void foo() {
System.out.println("It works");
}
});
}
@JSBody(params = "o", script = "main.api = o;")
private static native void exportAPI(Exported o);
}
This makes the foo() method available on the api
field of
the main()
method, after main has been invoked once to
register it. For example:
// Set up the api field
main();
// Invoke foo() on api
main().api.foo();
In this way you could expose multiple methods to create a full API.
You could distribute classes.js, and users of your API would follow
these steps:
- Load your classes.js
- Invoke
main()
- Invoke your api methods