The JavaScript Native Interface (JSNI) in the Google Web Toolkit (GWT) allows you to use parts of the GWT application outside of the app, and also to use JavaScript that it not part of the GWT app. This tutorial will show you how to read in JavaScript variables set on the page, and how to call GWT functions from the html page.
Getting an external variable
Instead of making an RPC call to get a variable needed by the GWT application on the page it is possible to set a JavaScript variable to the needed data either statically or dynamically while the page is being generated with PHP or another server side language. This variable is then grabbed by a JSNI function and usable by GWT. The variable is set like normal in the HTML or in an external JavaScript file like this:
var first_name = “Frank”;
A native function can then pull grab this variable from within the GWT Java code.
public native String getFirstName()/*-{
return $wnd.first_name;
}-*/;
The native function is commented out in the Java code since it is JavaScript and not Java, but is called like a normal function in the rest of the code. $win represents the JavaScript Window object which is used here to reference our first_name variable on the page. The function will return the value of the first_name variable, and it can then be used in the GWT Java code like any other variable.
Calling a GWT function externally
Many times it is easier to call a normal JavaScript function to open a GWT popup or cause some other kind of result then it is to have GWT add buttons to the page to do this. This can be difficult since GWT will obfuscate the code and change the name of the functions making it very hard to call them externally. The solution is to use JSNI to create a JavaScript function inside of GWT with a name that will not change, and then have that function call the internal function whose name could be anything after compiling.
From inside GWT a JavaScript function can be created on the Window object which can then be called anywhere in the HTML page.
public class BlueApp implements EntryPoint {
public void onModuleLoad() {
setShowTrigger(this);
}
public void runApp() {
Window.alert(’I am a GWT function’);
}
public native void setShowTrigger(BlueApp x)/*-{
$wnd.showBlueApp = function () {
x.@com.company.client.BlueApp::runApp()();
};
}-*/;
}
When this module is loaded it creates a JavaScript function called showBlueApp(), and nothing else. This function can then be called from the HTML page and it will execute the runApp() GWT function. The runApp function is referenced in the JavaScript with its full path which includes the module name. The variable x is the class itself and is passed in using “this”. Once it is called the JavaScript alert will appear.
The showBlueApp function would then be called like any other JavaScript function from the HTML.
onclick="showBlueApp()"