JavaFx WebEngine - 用(本地)文件覆盖网站的样式表
JavaFx WebEngine - Overwriting a website's stylesheet with (local) files
我想自定义我正在加载的网站的外观,所以我创建了一个小 test.css
文件,它除了更改所有 table 行的外观外什么都不做:
tr {
height: 22px;
background-image: url("test.png");
}
如何让 WebEngine 加载此文件并将页面自己的 CSS 规则替换为我的规则?
此外,我希望能够加载 页面特定的 css 文件 而不是所有页面的一个大文件。
我找到了 this page,但它只显示了如何 运行 通过 DOM 并手动为所需元素指定新样式。这当然不是我想要的。相反,我希望浏览器将我的文件用作 'user defaults'.
感谢任何帮助:)
首先我要声明,我希望你知道你在做什么,因为这些东西会严重损坏网站。
因此,您可以执行以下操作:
您从 WebEngine
中获取 Document
,检索 head
元素并向其添加一个 style
子元素,其中包含样式表的 src 位置想补充
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);
顺便说一句,JavaScript也可以用类似的方式添加,只是'script'而不是'style'
我想这样做来添加或替换任何规则:
String css = getFileAsString("style.css");
Document doc = webEngine.getDocument();
Element e = doc.getElementById("my_style");
e.setTextContent(css);
...给定
<style id="my_style"></style>
HTML 文档中的标签。
setUserStyleSheetLocation()
就是为这个目的而设计的:让网页的用户根据自己的需要设置样式。
用法:
webEngine.setUserStyleSheetLocation(styleSheetURL.toString());
我想自定义我正在加载的网站的外观,所以我创建了一个小 test.css
文件,它除了更改所有 table 行的外观外什么都不做:
tr {
height: 22px;
background-image: url("test.png");
}
如何让 WebEngine 加载此文件并将页面自己的 CSS 规则替换为我的规则? 此外,我希望能够加载 页面特定的 css 文件 而不是所有页面的一个大文件。
我找到了 this page,但它只显示了如何 运行 通过 DOM 并手动为所需元素指定新样式。这当然不是我想要的。相反,我希望浏览器将我的文件用作 'user defaults'.
感谢任何帮助:)
首先我要声明,我希望你知道你在做什么,因为这些东西会严重损坏网站。 因此,您可以执行以下操作:
您从 WebEngine
中获取 Document
,检索 head
元素并向其添加一个 style
子元素,其中包含样式表的 src 位置想补充
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);
顺便说一句,JavaScript也可以用类似的方式添加,只是'script'而不是'style'
我想这样做来添加或替换任何规则:
String css = getFileAsString("style.css");
Document doc = webEngine.getDocument();
Element e = doc.getElementById("my_style");
e.setTextContent(css);
...给定
<style id="my_style"></style>
HTML 文档中的标签。
setUserStyleSheetLocation()
就是为这个目的而设计的:让网页的用户根据自己的需要设置样式。
用法:
webEngine.setUserStyleSheetLocation(styleSheetURL.toString());