Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from WebView to controller and vice-versa in JavaFX

So I've found this tutorial on how to use google maps API in a Desktop JavaFX application.

The point is that I can't figure out how can I pass data from WebView (javascripts variables, jsons..) to controller and viceversa.

I'd like to make an textfield that on textinput to automaticaly search that address and add an marker there (and viceversa when I move the marker to populate the input). The javascript standalone is no problem for me, but I don't know how to call javascript functions from JavaFX controller or how to send back the variables from javascript (longitude, latitude, etc)

like image 214
user1236048 Avatar asked Jun 06 '12 16:06

user1236048


1 Answers

See the JavaFX WebView tutorial sections:

  • Processing JavaScript Commands
  • Making Upcalls from JavaScript to JavaFX

Make sure you use JavaFX 2.1+ when doing this, as JavaFX 2.0 does not have full support for upcalls from javaScript to JavaFX.


How to call javascript functions from JavaFX controller?

Java code to be executed after the document has loaded:

webView.getEngine().executeScript("<write your javascript here>");

How to send back the variables from javascript (longitude, latitude, etc)?

Here is a generic communication sample, replace it with the actual Java and JavaScript logic you want to execute.

Java code:

// Add a Java callback object to a WebEngine document once it has loaded.
webEngine.getLoadWorker().stateProperty().addListener(
  new ChangeListener<State>() {  
    @Override public void changed(ObservableValue<? extends State> ov, State oldState, State newState) {
      if (newState == State.SUCCEEDED) {
        JSObject win = (JSObject) webEngine.executeScript("window");
        win.setMember("app", new JavaApp());
      }
    }
  });
}
...
// JavaScript interface object
private class JavaApp {
  public void exit() {
    Platform.exit();
  }
}

JavaScript code (in this case embedded in an onclick handler for a html href):

<a href="about:blank" onclick="app.exit()">Exit the Application</a>
like image 139
jewelsea Avatar answered Oct 06 '22 09:10

jewelsea