如何在不重新加载页面的情况下从 Javafx 编辑 HTML 页面(在 webview 中)?
How to edit HTML page (in a webview) from Javafx without reloading the page?
这是我加载页面的方式,我想在浏览器中修改它
WebView browser = new WebView();
WebEngine engine = browser.getEngine();
String cwd = System.getProperty("user.dir");
String name = "\src\web\index.html";
engine.loadContent(getPATHtoHTML(cwd + name));
DOM 文档可用,可以修改。这将更新 WebView
的内容。以下示例只是将一些文本附加到正文中,但可以进行更复杂的操作:
@Override
public void start(Stage stage) {
WebView webView = new WebView();
WebEngine engine = webView.getEngine();
engine.loadContent("<html>"
+ "<body></body>"
+ "</html>");
TextField textField = new TextField();
Button button = new Button("add");
button.setOnAction(evt -> {
String text = textField.getText();
Document doc = engine.getDocument();
Element element = (Element) doc.getElementsByTagName("body").item(0);
element.appendChild(doc.createTextNode(text));
});
Scene scene = new Scene(new VBox(webView, textField, button));
stage.setScene(scene);
stage.show();
}
如果你也想修改文件,也可以将结果输出到文件:
DOMSource domSource = new DOMSource(engine.getDocument());
StreamResult result = new StreamResult(outputFile);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.transform(domSource, result);
这是我加载页面的方式,我想在浏览器中修改它
WebView browser = new WebView();
WebEngine engine = browser.getEngine();
String cwd = System.getProperty("user.dir");
String name = "\src\web\index.html";
engine.loadContent(getPATHtoHTML(cwd + name));
DOM 文档可用,可以修改。这将更新 WebView
的内容。以下示例只是将一些文本附加到正文中,但可以进行更复杂的操作:
@Override
public void start(Stage stage) {
WebView webView = new WebView();
WebEngine engine = webView.getEngine();
engine.loadContent("<html>"
+ "<body></body>"
+ "</html>");
TextField textField = new TextField();
Button button = new Button("add");
button.setOnAction(evt -> {
String text = textField.getText();
Document doc = engine.getDocument();
Element element = (Element) doc.getElementsByTagName("body").item(0);
element.appendChild(doc.createTextNode(text));
});
Scene scene = new Scene(new VBox(webView, textField, button));
stage.setScene(scene);
stage.show();
}
如果你也想修改文件,也可以将结果输出到文件:
DOMSource domSource = new DOMSource(engine.getDocument());
StreamResult result = new StreamResult(outputFile);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.transform(domSource, result);