简体   繁体   中英

Calling a GWT Java function from an html script tag

I have a GWT project and I would like to add a script tag to the main html file of the GWT project that calls a Java function located in my client code.

According to the documentation I should add something like the following html tag:

<script type='text/javascript'> 
this.@com.myCompany.myProject.client.myClass::myFunction();
</script>

where com.myCompany.myProject.client.myClass is the class path and myFunction is the java function I would like to call.

When I try this with the following implementation of myFunction nothing happens:

public void myFunction() {
    HTMLPanel panel = new HTMLPanel("I have been called");
    RootPanel.get().add(panel);
}

That is, myFunction is not being called.

But when I make the same call from a JSNI method, then it works.

Is it maybe not possible to do the call from an html script, or am I doing something wrong?

Thanks!

  1. What you are trying to do does not work because GWT compiler renames all identifier names to minimize produced code size: so myFunction() exists, but it's called something else.

  2. You were looking at old version of documentation. In the latest version this is all explained: Calling a Java Method from Handwritten JavaScript

The solution - add an additional method somewhere:

public static native void exportMyFunction() /*-{
   $wnd.myFunction =
      $entry(@com.myCompany.myProject.client.myClass::myFunction());
}-*/;

then in your app initialization you must call EnclosingClass.exportMyFunction() . Then in hand-crafted javascript you can access it via:

window.myFunction();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM