The DOM document is available and can be modified. This updates the content of the WebView
. The following example simply appends some text to the body, but more complex manipulations are possible:
@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();
}
If you also want to modify the file, you could also output the result to a file:
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);
engine.loadContent("new Content...")
; To edit HTML you have to usejavafx.scene.web.HTMLEditor
. – Arsenic