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

若如初见. 提交于 2019-11-29 10:48:15
Andrey Chaschev

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.

I just found out that using the <base> tag in the HTML also does the trick:

<html>
    <head>
        <title>The slash at the end of the href is important!</title>
        <base href="file:///absolute/path/to/your/docroot/" />
    </head>
    <body>
        <img src="image.png"/>
    </body>
</html>

If you load the above code via engine.loadContent(String) then image.png will be loaded from /absolute/path/to/your/docroot/image.png.

This method is easier if you need to load multiple resources since you only have to specify the absolute path at a single place.

This has been tested with WebView of Java 8u25.

You just need to load your HTML page using the load() method of the WebEngine. The loading of the associated CSS and JavaScript will be done for you by the WebEngine.

Here is how I have loaded AceEditor into a WebView:

and the code to do this was just of two lines:

engine = webView.getEngine();
engine.load("file:///home/littlejavachild/Downloads/AceEditor/ace-builds-master/MyTry.html");  

The loading of JavaScript source and CSS is handled for me by the engine.

The docs for the method is here:

public void load(java.lang.String url)

Loads a Web page into this engine. This method starts asynchronous loading and returns immediately.

Parameters: url - URL of the web page to load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!