I have a variable in Javascript, which toggles between true
and false
when full-screen mode is switched on and off, respectively. Now I want to access that variable in my GWT
code, and do some actions accordingly. Can anyone tell me how to do it? I couldn't understand it from the Google documentation on JSNI
...
Asked
Active
Viewed 5,801 times
4

SexyBeast
- 7,913
- 28
- 108
- 196
-
The selected answer doesnt work ! – Mar 18 '13 at 13:02
2 Answers
8
In JavaScript
var mybool = true;
your JSNI method in MyClass class ;
public static native boolean getNativeVariableType(String jsVar)/*-{
return eval('$wnd.' + jsVar);
}-*/;
Finally using in GWT ;
boolean getFormJs = Myclass.getNativeVariableType("mybool");
As @dodoot raised the point you can try this return !!$wnd[jsVar]
to get ridoff eval
function side effects.
As @manolo said if you are using gwtQuery it will be more handy by writing simply $(window).prop("mybool")
.

Suresh Atta
- 120,458
- 37
- 198
- 307
-
2-1, eval is always a security issue in javascript (as well as in other scripting languages). Its better (and shorter) just to test if the var exists, change all the jsni block by `return !!$wnd[jsVar]` – Mar 01 '13 at 15:18
-
@Dodoot .Agreed .as long as you are on client side the eval wont be cause any damage..if you hit the server and then using eval will cause injections.Of course its better to take this point into consider .Cheers :) – Suresh Atta Mar 01 '13 at 15:34
-
2@Baadshah your second solution doesnt work at all!!, It always look for the property 'jsVar' in window instead of replacing with the value passed as parameter. – Mar 18 '13 at 13:02
7
Just as a curiosity, for simple things like this, you can avoid writing jsni methods by taking advantage of certain jsni methods already present in gwt overlay classes.
So in your case you can get the window object, and casting it to an element, read its properties with getters from the Element
class :
Element $wnd = (Element)Document.get().<Element>cast().getPropertyObject("defaultView");
boolean mybool = $wnd.getPropertyBoolean("mybool");
Adding the gwtquery library to your project, the code is much simpler:
boolean mybool = $(window).prop("mybool");

Manolo Carrasco Moñino
- 9,723
- 1
- 22
- 27
-
-
-
well, gwtquery aka gquery is an amazing library to manipulate dom and js objects from java, and @Manolo is the guy behind it :-) – Mar 01 '13 at 19:27
-
@Manolo GwtQuery makes it simple, and I believe you are the project lead for that right? – Apr 07 '13 at 06:26