dadoosh dadoosh - 1 year ago 116
CSS Question

JavaFx WebEngine - Overwriting a website's stylesheet with (local) files

I'd like to customise the appearance of a website that I am loading, so I created a little

file that does nothing but changing the look of all table rows:

tr {
height: 22px;
background-image: url("test.png");

How do I get he WebEngine to load this file and replace the page's own CSS rules with mine?
Also, i'd like to be able to load page-specific css files and not one huge file for all pages.

I found this page, but it only shows how to run through the DOM and assign a new style to the desired elements by hand. This is, of course, not what I want. Instead, I'd like the browser to use my files as 'user defaults'.

Thx for any help :)

Answer Source

First of I have to state, that I hope you know what you are doing, as these things can seriously damage a web site. So here is what you can do:

You grab the Document from the WebEngine, retreave the head element and add a style child element to it, containing the src location of the stylesheet you want to add.

Document doc = webView.getEngine().getDocument();
URL scriptUrl = getClass().getResource(pathToAttachedDocument); // pathToAttachedDocument = CSS file you want to attach
String content = IOUtils.toString(scriptUrl); // Use Apache IO commons for conveniance
Element appendContent = doc.createElement("style");

By the way, JavaScript can be added in a similar way, it's just 'script' instead of 'style'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download