Google Web Toolkit (Beta)
Search this site:

# JavaScript Native Interface (JSNI)

The GWT compiler translates Java source into JavaScript. Sometimes it's very useful to mix handwritten JavaScript into your Java source code. For example, the lowest-level functionality of certain core GWT classes are handwritten in JavaScript. GWT borrows from the Java Native Interface (JNI) concept to implement JavaScript Native Interface (JSNI).

Writing JSNI methods is a powerful technique, but should be used sparingly. JSNI code is less portable across browsers, more likely to leak memory, less amenable to Java tools, and hard for the compiler to optimize.

We think of JSNI as the web equivalent of inline assembly code. You can:

- Implement a Java method directly in JavaScript
- Wrap type-safe Java method signatures around existing JavaScript
- Call from JavaScript into Java code and vice-versa
- Throw exceptions across Java/JavaScript boundaries
- Read and write Java fields from JavaScript
- Use hosted mode to debug both Java source (with a Java debugger) and JavaScript (with a script debugger, only in Windows right now)

Tip
When accessing the browser's window and document objects from JSNI, you must reference them as `$wnd` and `$doc`, respectively. Your compiled script runs in a nested frame, and `$wnd` and `$doc` are automatically initialized to correctly refer to the host page's window and document.

## Specifics