WebView, the other JavaFX UI

Aside from its native UI facilities, JavaFX provides a WebView that’s a fully-featured embedded HTML5 browser. The underlying WebEngine is a modified Webkit engine which comes as part of the freely available JavaFX source code.

  • For JavaFX 2.2.4 (part of Java SE 7), Oracle offered a separate download. This code was based on Webkit 535.21, released on 17 February 2012.
  • For JavaFX 8 (part of Java SE 8), there is no separate download (yet?) but you can grab the entire OpenJFX source (42.4 MB for the BZ2 package). The included WebEngine is based on Webkit 537.44, released on 6 June 2013.

The Webkit release dates are available in the Webkit version tracker. The Webkit version information can be found in the following file within the OpenJFX source package:

modules/web/src/main/native/Source/WebCore/Configurations/Version.xcconfig

Sample Application

WebView could run all the HTML5 sample applications I threw at it. The one I’d like to showcase here is HTML5 Chess, a terrific open source project by Stefano Gioffré. Although sadly abandoned today, the final release is a complete working chess program written in HTML and JavaScript.

You can play the demo online but for WebView hosting you should download the latest version. Extract the htmlchess folder from the archive, and then run this tiny JavaFX application from the directory that contains htmlchess:

package org.kynosarges;

public class WebViewTest extends javafx.application.Application {

    @Override
    public void start(javafx.stage.Stage primaryStage) {

        // path in current directory for WebEngine.load()
        final String html = "htmlchess/example.html";
        final java.net.URI uri = java.nio.file.Paths.get(html).toAbsolutePath().toUri();

        // create WebView with specified local content
        final javafx.scene.web.WebView root = new javafx.scene.web.WebView();
        root.getEngine().load(uri.toString());
        root.setZoom(javafx.stage.Screen.getPrimary().getDpi() / 96);

        primaryStage.setTitle("HTML Chess");
        primaryStage.setScene(new javafx.scene.Scene(root, 1100, 820));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

There’s just one tricky part: WebEngine.load() requires absolute file paths, marked with the URI prefix file://. We want to load from a relative location, namely the current directory, so we need to fix up the location using Path and URI. If you’re running from within NetBeans, note that the current directory is the one above the dist folder containing the JAR file. Run your executable JAR and you should see the following window (after clicking “Both” to show both the 2D and 3D chessboard):

HTML Chess

HTML Chess (click for original size)

The screenshot was taken at 100% DPI scaling since the page has a lot of content – the Portable Game Notation (PGN) reader below the lower window border is not even visible! As of JavaFX 8 WebView supports full page zooming which the sample code matches to the current system DPI setting. A text-only zoom function is also available, though not terribly useful.

WebView Advantages

JavaFX supports rich interactions between the Java application and its hosted WebView. You can access the HTML document through the usual Java org.w3c.dom API, attach Java handlers to selected JavaScript events, use executeScript to run arbitrary JavaScript code snippets, and let JavaScript functions call back to arbitrary Java methods.

Regarding HTML5 capabilities, JavaFX 8 added web sockets, web workers, and web fonts, along with printing HTML pages. Of course WebView can simply show remote websites or local help pages, but there are a few reasons to consider moving your main UI into WebView:

  • Tragically, WebView page zoom offers better high DPI support than native JavaFX controls since JavaFX still doesn’t scale drawing coordinates…
  • Create two-tiered cross-platform applications, with a common baseline written in HTML/JS that runs everywhere, and extra features provided via embedded JavaFX deployment where possible.
  • Run HTML5 apps on desktop systems that lack a sufficiently compatible web browser. You actually don’t need an installed modern JVM either, as the JVM is perfectly capable of private deployment. This can be automated with JavaFX native packaging.
  • If you share the growing consensus that HTML/JS is the future of client-side programming, get ready for that future by targeting WebView, supplemented by Java(FX) for the parts where HTML is still lacking or JavaScript is too slow.

In the HTML Chess example, some obvious improvements would be better management of local PGN files, or an alternative Java implementation for the slow JavaScript turn prediction (enabled by “Machine Meditation Level”). The idea of a JavaFX client application with an HTML UI might seem weird at first, but I think it’s an interesting option – and probably a necessary one, given the rapid spread of HTML/JS as a standard UI technology.

Related Projects

After posting this article I discovered a number of related projects on the web, both old and new. It seems the concept of combining local applications with browser engines is gaining traction. This section, last updated on 29 April 2014, collects links with brief introductions to such projects.

  • Intel created the free node-webkit in 2011, a multi-platform runtime that packages Chromium with node.js for pure client-side execution of HTML5 applications. Also see this tutorial.
  • Sanjeev Radhakrishnan’s Chrome Is The New C Runtime proposes using Chromium as a fundamental library for native C++ development. He wants to build native GUIs and mostly use Chromium for networking, but it should be simple to create a cross-platform HTML5 UI in Chromium instead.
  • GitHub’s Atom editor calls itself “web native.” The editor is written in HTML/JS and dynamically updated, but executes in a native Chromium application in order to get around JavaScript’s security restrictions and browser compatibility issues.
  • Java APIs for HTML, also somewhat confusingly known as “DukeScript,” aims to provide a complete framework for Java applications with HTML5 UIs. The current implementation is based on WebView and demonstrated by NetBeans’ Geertjan Wielenga: part 1, part 2.
  • Apache Cordova (née PhoneGap) allows deployment of HTML/JS applications to mobile app stores using native wrappers. Supported platforms include iOS, Android, and Windows Phone. Microsoft is working on a Visual Studio 2013 plugin that adds Windows Store support.

3 thoughts on “WebView, the other JavaFX UI

  1. fraggle

    Hey, i stumbled upon your article while searching for a solution to “fix” the high dpi “issue” on javafx webview. I just wanted to ask, if you maybe found some workaround or anything else to get rid of wrong dpi compensation on webview? At the moment i’m developing a standalone program where i need the webview for displaying a rich html editor which scales really bad on small screens with high resolutions&dpi :(

    Reply
    1. Christoph Nahr Post author

      You can try changing the fontScale property, but if that breaks the layout you’ll have to wait for Java 8 (or use the developer preview) with the new zoom property, as shown in my code sample. I don’t think there’s another workaround at this time, sorry.

      Reply
  2. Pingback: openJSDE, my HTML5 Desktop framework [14.04.2014] | GameplayJDK's Blog

Leave a Reply