Home / Java Patterns and Pitfalls     frequal.com

TeaVM: Calling Java From JavaScript

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.

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:
  1. Load your classes.js
  2. Invoke main()
  3. Invoke your api methods

Last modified on 5 Sep 2021 by AO

Copyright © 2024 Andrew Oliver