How to run JavaScript function from GWT Java using JSNI?

I canโ€™t understand from the manual: how to actually run the JS function from Java?

For example, I have a function in my html page:

<script type="text/javascript" language="javascript"> function foo() { alert('Foo!'); } </script> 

The following module displays two buttons, only the second of which works:

 public class Test_GoogleWeb_JSNI_01 implements EntryPoint { public void onModuleLoad() { Button fooButton = new Button("Foo!"); fooButton.addClickHandler(new ClickHandler(){ public void onClick(ClickEvent event) { fooRunner(); }; }); HTML fooButtonNative = new HTML(); fooButtonNative.setHTML("<input type='button' value='Foo Native' onclick='foo()'>"); RootPanel rootPanel = RootPanel.get(); rootPanel.add(fooButton); rootPanel.add(fooButtonNative); } public static native void fooRunner() /*-{ foo(); }-*/; } 

The manual says that the built-in functions are implemented inside a nested frame, which explains the situation. But how to run JS functions then?

UPDATE 1 Next work.

Java:

 public static native void fooRunner() /*-{ $doc.fooRunner(); }-*/; 

JS:

 <script type="text/javascript" language="javascript"> document.fooRunner = function foo() { alert('Foo!'); } </script> 

Is there a better way?

+8
java gwt jsni
source share
1 answer

You yourself answered your own question. There is no better way for a very simple reason: there are several ways to deploy a GWT application; working in an iframe is just one option. So why you should use the $ wnd variable to access the external JS function, so if you switch the linker, your code will work fine.

+4
source share

All Articles