When styling a WebView
, it's important to apply the stylesheet directly to the WebView
itself and not the content it displays. This means that the CSS will affect the WebView
itself and not the HTML content within. Keep in mind that JavaFX scene graph nodes do not support the calc
function, so refer to the JavaFX CSS reference for valid CSS properties.
If your goal is to style the HTML document displayed by the WebView
, you'll need to reference the stylesheet within the HTML document itself in the traditional way.
To load a stylesheet dynamically, you can manipulate the HTML document after it has been loaded. Consider the following approach:
private void addStylesheet(Document doc, String cssLocation) {
Element docElement = doc.getDocumentElement();
NodeList heads = docElement.getElementsByTagName("head");
Element head;
if (heads.getLength() == 0) {
head = doc.createElement("head");
docElement.appendChild(head);
} else {
head = (Element) heads.item(0);
}
Element link = doc.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", cssLocation);
head.appendChild(link);
}
Then, implement the following:
WebEngine engine = webView.getEngine();
engine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED) {
addStylesheet(engine.getDocument(), "http://page.com/style.css");
}
});
engine.load(/* your html ... */);