Skip to content

Instantly share code, notes, and snippets.

@icodealot
Created October 26, 2017 14:19
Show Gist options
  • Save icodealot/5e113346bd841207032e07d9c93faacd to your computer and use it in GitHub Desktop.
Save icodealot/5e113346bd841207032e07d9c93faacd to your computer and use it in GitHub Desktop.
// This is a minimal JavaFX web browser written in JavaScript
// for Nashorn. Requires Java 1.8+ and I recommend JJS[.exe]
//
// Usage:
// jjs browse.js -- [URL or File.html]
// Declare class references from Java packages
var Application = Java.type("javafx.application.Application");
var Scene = Java.type("javafx.scene.Scene");
var WebView = Java.type("javafx.scene.web.WebView");
var Paths = Java.type("java.nio.file.Paths");
// Declare global variables and functions
var web;
var url = arguments[0].trim().replace("\"","");
if (!url.startsWith("http")) {
url = Paths.get(url).toUri().toString()
}
var WebApp = Java.extend(Application, {
start: function(win) {
web = new WebView();
web.engine.load(url);
var scene = new Scene(web, 800, 600);
win.title = url;
win.scene = scene;
win.show();
}
});
// Start the JavaFX web browser in a separate thread
// ---- > because Application.launch() is a blocking call.
new java.lang.Thread(function () {
Application.launch(WebApp.class, null);
}).start();
@icodealot
Copy link
Author

As noted by A. Sundararajan on twitter you could also consider writing this script without extending javafx.application.Application. In this case you would run jjs with an extra flag such as:

jjs -fx browse.js -- https://google.com

Here is an example for your reference on a Nashorn script that is a JavaFX application from start to finish. The advantage of this approach is that you can simplify the script slightly to create your JavaFX application, however, you lose some control and maybe understanding of what is happening behind the scenes.

Also, if you want to embed the WebView in a larger application where the script is not intended to be entirely a JavaFX application then you may want to stick with the approach shown in this Gist. (Keep in mind that Application.launch() is a blocking call and handle your threads accordingly.) Here is an example project where you might see a JavaFX application integrated as part of a larger non-JavaFX application / script.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment