简体   繁体   中英

gwt/jsni- Pass a String from external JS to Java

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.

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.

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