WebEngine.getDocument
返回 ,而不是 JavaScript 文档,您希望通过代码来判断。org.w3c.dom.Document
不幸的是,打印出来需要相当多的编码。您可以尝试从“将 org.w3c.dom.Document 打印到 stdout 的最短方法是什么?”中尝试解决方案,请参阅下面的代码。org.w3c.dom.Document
请注意,您需要等到加载文档后再使用 。这就是为什么在这里使用:Document
LoadWorker
public void start(Stage primaryStage) {
WebView webview = new WebView();
final WebEngine webengine = webview.getEngine();
webengine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == Worker.State.SUCCEEDED) {
Document doc = webengine.getDocument();
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(doc),
new StreamResult(new OutputStreamWriter(System.out, "UTF-8")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
webengine.load("http://stackoverflow.com");
primaryStage.setScene(new Scene(webview, 800, 800));
primaryStage.show();
}