Inserting javascript into GWT using JSNI
Sure the whole point of using GWT is so you don’t have to mess with that abortion known as javascript, but sometimes you may need (or actually want) to use javascript for something in your GWT application. For this we use JavaScript Native Interface (JSNI). JSNI uses the native keyword, so if you’ve used JNI (Java Native Interface) in the past you’ll have little to get used to.
I needed to use JSNI recently. Since GWT doesn’t provide a way to bring the browser to the front or top like javascript does with it’s self.focus(); I was able to use JSNI to call that line of javascript. Here’s a quick example:
public static native void bringToFront() /*-{ self.focus(); }-*/;
Then all you need to do is call the bringToFront() method like you normally would. Along with noticing in the native keyword, you’ll immediate see that the block looks commented out. JSNI has two tokens to mark the beginning and end of your javascript the /*-{ marks the begin and }-*/ marks the end. Everything in between those tokens are assumed to be javascript.
There are more examples on GWT JSNI site.
Awesome post. Gotta love technology. Thanks!
One of the best technology’s Google have ever made. Nice article by the way