0

How can I call from external JS with JSNI?

For example:

//Some external JS code 
         ...
        this.onFeatureClick = function(event) {
        ...
        var name = "Batman";
        passToJava(name); //Invoke java method and pass String name
        };

I tried this here:

 public void onModuleLoad() {
     ...
     nativeVariableName(); //Call native method
 }

 public static void passToJava(String name) {
    System.out.println(name);
 }

public native String nativeVariableName() /*-{
            $wnd.passToJava = function(name) {
            @com.google.myproject.webinterface.client.MyWebInterface::passToJava(Ljava/lang/String;)(name);
            }; }-*/;

I don't even know if the call from JavaScript works. Thanks.

2
  • take a look at the gwt docs, the first section explains how to send a variable from JavaScript to Java: code.google.com/webtoolkit/doc/latest/… Commented Jan 8, 2012 at 21:00
  • public static native void alert(String msg) /*-{ $wnd.alert(msg); }-*/; Commented Jan 8, 2012 at 21:00

1 Answer 1

2

This code works just fine. I don't know where do you expect to see result of invocation of System.out.println, but looks like you are looking into wrong place. Replace System.out.println with Window.alert and see for yourself. If it doesn't work, it means that error is in some other place:

  • Check if the function is correctly exposed (open console in browser, and type window.passToJava, if it displays null, function wasn't exposed)
  • Check if onFeatureClick is called correctly.
Sign up to request clarification or add additional context in comments.

2 Comments

Another way of printing debug messages is to use the method com.google.gwt.core.client.GWT.log(String). That way, it will be visible in the console utility for the hosted mode. That way only developers will ever see such messages but users will never be bothered even if you forget to remove the calls later.
Thanks, it helped. If I add a function passToJava(){...} in the external JS code, then the call works onclick. However, nothing happens in my gwt code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.