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>
source share