How to load both html and javascript into webengine from loadContent()?

user2799603 picture user2799603 · Nov 23, 2013 · Viewed 10.5k times · Source

Could someone provide some suggestions on how to load the following onto webviewer from loadContent()?

http://jsbin.com/aqupun/6/edit

I was trying to do something like this, but it doesn't seem to work. Thanks!

    Scanner sc1 = new Scanner(new File("src/web/web.html"));
    String webStr = sc1.useDelimiter("\\Z").next();

    Scanner sc2 = new Scanner(new File("src/web/data.js"));
    String dataStr = sc2.useDelimiter("\\Z").next();

    Scanner sc3 = new Scanner(new File("src/web/cytoscape.min.js"));
    String cytoStr = sc3.useDelimiter("\\Z").next();

    Scanner sc4 = new Scanner(new File("src/web/jquery.min.js"));
    String jqueryStr = sc4.useDelimiter("\\Z").next();

    webEngine.loadContent(cytoStr, "text/javascript");
    webEngine.loadContent(jqueryStr, "text/javascript");
    webEngine.loadContent(dataStr, "text/javascript");
    webEngine.loadContent(webStr, "text/html");

Answer

Andrey Chaschev picture Andrey Chaschev · Nov 24, 2013

You first need to put these three files to the resources on the same level or on the hard drive.

To load your content directly from memory you can use

webView.getEngine().loadContent("your html")

From JavaDoc:

public void loadContent(String content)

Loads the given content directly. This method is useful when you have content composed in memory, or loaded from some system which cannot be reached via a URL.

Be aware though that the linked resources should be available by their urls, i.e. on disk or in resources. To reflect dynamic changes in your web app I suggest you to call Java from JS. This can be done by providing Java object into JS app: Communication between JavaFX and JavaScript inside WebView, using JSObject

Here you may find a browser demo and a simplified WebView component: Java GUI to display webpages and return HTML.