Introduction
JavaFX’s integration with web pages is quite impressive – you can query the DOM, execute arbitrary JavaScript and get results back.
In addition, you can trigger changes on the Java-side from the web page. In this brief introduction we’ll look at printing out the ID of each clicked on element in the console.
The power of this is really the ability to trigger Java events from within an embedded website, neatly blurring the division between your standalone app and your website.
Process
First we’ll need something to actually perform the method on the Java side – as an example, we’re just casting the object to an HTML element and sout
ing its ID.
1 2 3 4 5 6 7 8 |
public class WebController { public void printId(Object object) { if (org.w3c.dom.html.HTMLElement.class.isAssignableFrom(object.getClass())) { org.w3c.dom.html.HTMLElement it = (org.w3c.dom.html.HTMLElement) object; System.out.println("Id is " + it.getId()); } } } |
If we’re loading our page using something like
1 2 |
final WebEngine webEngine = webview.getEngine(); webEngine.load("http://localhost/demo/clickHandler/"); |
Then we can wait for a succesful loading before injecting our JavaScript.
1 2 3 4 5 6 7 8 9 10 |
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() { @Override public void changed(ObservableValue<? extends State> ov, State oldState, State newState) { if (newState == State.SUCCEEDED) { JSObject window = (JSObject) webEngine.executeScript("window"); window.setMember("clickController", new WebController()); } } } ); |
There is now a JavaScript object called clickController available – calling the methods on this JavaScript object will result in the methods being called on the Java side.
As an example, this jQuery will call the Java method each time anything is clicked on.
1 2 3 4 5 6 7 |
$(function () { $('*').click(function (event) { event.preventDefault(); event.stopPropagation(); clickController.printId(this); }); }); |
End!
There’s a lot that can be done quite easily using this kind of interaction – I’m sure we’ll be seeing more of it as it catches on.
Leave a Reply