JavaFX and JavaScript – calling Java from JavaScript

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 souting its ID.

If we’re loading our page using something like

Then we can wait for a succesful loading before injecting our JavaScript.

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.

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.

Tagged with: , ,
Posted in Java, Javascript

Leave a Reply