JavaFX's WebEngine, which is part of the WebView node, does not seem to be able to display images whose paths are declared as a "normal" file path, like /home/user/images/image.png, unlike conventional browsers. It will however display the image when adding a scheme to the URI, which would look like that: file:///home/user/images/image.png.
Why is that?
Here is some context to why I am asking this question:
I have some HTML in memory that contains img tags pointing to image files stored on disk. The paths used to identify those images are absolute, so in the form of /home/user/images/image.png. That HTML then gets loaded using the WebEngine's loadContent method. However, as mentioned above, the WebEngine will not display those images. So the only solution I have yet come up with is to go through the HTML and append the scheme to each path. But I find this to be quite an ugly solution...
Relative URLs in an HTML page will be resolved in the context of the location of the page. Thus if you open an HTML file in a browser, the location of the page is
file:///path/to/file.html. An absolute file path/home/user/images/image.pngresolved relative to that URL will resolve, as expected, tofile:///home/user/images/image.png. In other words, the relative resolution of the URL preserves the schemefile://.In the case where you load HTML into the JavaFX
WebViewusing theloadContentmethod, there is no location (the HTML is simply in memory) and thus resolution of a relative URL will not work (there is no scheme).I can think of two solutions. One requires a change to the HTML, which may or may not be convenient. The solution here is simply to add a
<base>element to the<head>of the HTML, specifyingfile:///as the document base.Here is a complete example demonstrating this:
If it's not possible (or desirable) to modify the HTML for some reason, the other solution is to write the HTML to a temporary file and load it from the file. This is the same example using this approach. You probably want to clean up the file afterwards, which involves a little work (though not too much).