Search code examples
javascriptgwtjsni

Call GWT Method from Handwritten JavaScript


I'd like to execute some js method from browser console to call gwt code. For ex.

showMyWindow();

js:

function showMyWindow() {
// call gwt code from here MyWindow::showMe()
}

gwt:

class MyWindow extends Window {
  public static showMe {
    MyWindow wnd = new MyWindow();
    wnd.show();
  }
}

How to do that? Thanks.


Solution

  • As outlined in the JSNI documentation on calling GWT Java from handwritten Javascript, you need to expose the showMyWindow function so your other javascript can be called. Sometime before you want to actually call showMyWindow in JS, run a function like this.

    public static native void exportShowMe() /*-{
      $wnd.showMyWindow = $entry(@my.package.client.MyWindow::showMe());
    }-*/;
    

    After you have called that, you'll be able to call showMyWindow() in regular JS and have your static method called.

    As an aside, your showMe method probably needs a return type, in this case, most likely void.