How to transfer data from WebView to a controller and vice versa in JavaFX

So, I found this tutorial on how to use google map APIs in JavaFX desktop application.

The fact is that I can’t understand how to transfer data from WebView (javascripts variables, jsons ..) to the controller and vice versa.

I would like to create a text field that on textinput automatically searches for this address and adds a marker there (and vice versa when I move the marker to fill in the input). Stand-alone javascript is not a problem for me, but I don’t know how to call javascript functions from a JavaFX controller or how to send variables back from javascript (longitude, latitude, etc.).

+6
source share
1 answer

See the JavaFX WebView tutorial section:

  • JavaScript Command Processing
  • Linking JavaScript to JavaFX

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


How to call javascript functions from JavaFX controller?

Java code that will be executed after loading the document:

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

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

Here is a general communication example, 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, built-in to the onclick handler for html href):

 <a href="about:blank" onclick="app.exit()">Exit the Application</a> 
+8
source

Source: https://habr.com/ru/post/917460/


All Articles