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

后端 未结 3 1401
眼角桃花
眼角桃花 2020-12-11 12:51

I\'d like to customise the appearance of a website that I am loading, so I created a little test.css file that does nothing but changing the look of all table r

相关标签:
3条回答
  • 2020-12-11 13:20

    setUserStyleSheetLocation()was designed for that very purpose: to let the user of the web page, style it as they want.

    Usage:

    webEngine.setUserStyleSheetLocation(styleSheetURL.toString());

    0 讨论(0)
  • 2020-12-11 13:32

    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, retrieve 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");
    appendContent.appendChild(doc.createTextNode(content));
    doc.getElementsByTagName("head").item(0).appendChild(appendContent);
    

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

    0 讨论(0)
  • 2020-12-11 13:33

    I would do like this to ADD or REPLACE any rules :

    String css  = getFileAsString("style.css");
    Document doc = webEngine.getDocument();
    Element e = doc.getElementById("my_style");
    e.setTextContent(css);
    

    ... given a

    <style id="my_style"></style> 
    

    tag in the HTML document.

    0 讨论(0)
提交回复
热议问题