JSNI is a means to include raw JavaScript code in a GWT application written in Java. JSNI is the web equivalent of inline assembly code.
JSNI (JavaScript Native Interface) can be used to integrate GWT with an existing JavaScript library, or to access low-level browser functionality not exposed by the GWT class API's. JSNI allows you to integrate JavaScript directly into your application's Java source code.
A JSNI method is declared native
and contains JavaScript code in a specially formatted comment block between the end of the parameter list and the trailing semicolon. JSNI methods are called just like any normal Java method, and can accept parameters, call methods on Java objects, and return values to the Java-side of the application.
class JavaScriptCalculator
{
public static native int add(int n, int m)
/*-{ return n + m; }-*/;
public static void main(String[] args)
{
System.out.println(JavaScriptCalculator.add(4, 8));
}
}
The names $wnd
and $doc
are used to access the browser's window
and document
objects from JSNI.
public static native void say(String message)
/*-{ $wnd.alert(message); }-*/;