Skip to content

Interacting with JavaScript

Volker Berlin edited this page Apr 3, 2022 · 3 revisions

An HTML page and JavaScript are required to run WebAssembly. It cannot be displayed like an image alone. This starts with loading the WebAssembly bytecode and continues with calling the first method, accessing the DOM and completing the lean functionality of WebAssembly. There are annotations to declare the bindings between Java and WebAssembly.

@Export

With the @Export annotation you can mark a method as callable from JavaScript. By default the method name is used as export name. But you can also define another name. The method must be a static method. There must be minimum one method with this annotation which you call as first method.

@Import

With the @Import annotation you give WebAssembly the possibility to call JavaScript code or an API of the WebAssembly runtime (WASI). But WebAssembly can only call JavaScript code that you have pass when instantiating. To simplify this JWebAssembly also create a JavaScript file that contains code for all imports. There are 2 types of imports. You can import a completely JavaScript object like the Math object. Or you define specific JavaScript code in the annotation like in currentTimeMillis.

@Replace

One of the most important use cases for the @Import annotation is a replacement for a native Java method. This is possible with the @Replace annotation. You need to declare the internal Java signature of the method that should replaced. If you have a typing error then it has no effect.

@Partial

Extends an existing class or replace more as a single method. A sample is the String class.

@WasmTextCode

Declare a method in WebAssmebly byte code. This can be used for high optimized code or to access WebAssembly native features. A sample is the Math class.

Clone this wiki locally