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)

6/6/2012 4:13:19 PM

Accepted Answer

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.
  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() {

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>
6/7/2012 5:16:19 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow