HTML 文档位于 WebEngine 的document http://docs.oracle.com/javase/8/javafx/api/javafx/scene/web/WebEngine.html#documentProperty属性,但它是在后台加载的,所以你must等待它加载:
WebView1.getEngine().documentProperty().addListener((o, old, doc) -> listenToButton(doc));
WebView1.getEngine().load(new File("C:/Users/hadhe/Desktop/boots/index.html").toURI().toURL().toString());
文档对象是一个常规的 XML 文档,因此如果按钮有id
属性,您可以轻松检索它:
private void listenToButton(Document doc) {
if (doc == null) {
return;
}
String id = "app-action-button";
Element button = doc.getElementById(id);
// ...
}
如果按钮没有 id,您可以使用 XPath 搜索它:
private void listenToButton(Document doc) {
if (doc == null) {
return;
}
XPath xpath = XPathFactory.newInstance().newXPath();
Element button = (Element)
xpath.evaluate("//input[type='button']", doc,
XPathConstants.NODE);
// ...
}
最后,您可以向按钮添加 DOM 事件侦听器,如中所述Web引擎文档 http://docs.oracle.com/javase/8/javafx/api/javafx/scene/web/WebEngine.html:
((EventTarget) button).addEventListener("click", e -> doSomeAction(), false);