我需要帮助找出如何使用javaFx WebEngine.executeScript正确点击链接。
我尝试了代码:webEngine.executeScript("document.querySelectorAll(\"a[ajaxify^='/ajax/messaging/composer.php?']\")[0].click();");
但是,每次运行应用程序时,执行上述代码时都会生成以下错误。错误如下:
netscape.javascript.JSException: TypeError: 'undefined' is not a function
at com.sun.webpane.platform.WebPage.twkExecuteScript(Native Method)
at com.sun.webpane.platform.WebPage.executeScript(WebPage.java:1438)
at javafx.scene.web.WebEngine.executeScript(WebEngine.java:811)
at javafxapplication2.MainController$4.run(MainController.java:201)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
at java.lang.Thread.run(Thread.java:722)
我还验证了该对象存在但由于某种原因调用click()函数不起作用。提前感谢您的帮助。
答案 0 :(得分:0)
我正在使用javafx 8,但它应该是相同的想法。如果您创建MouseEvents对象,则应该能够单击任何元素。
this.webEngine.executeScript("(function () {" +
"var element = document.querySelector('a');" +
"var bounds = element.getBoundingClientRect();" +
"var evt = document.createEvent('MouseEvents');" +
"evt.initMouseEvent('click', true, false, window," +
"1, 0, 0, bounds.left, bounds.top," +
"false, false, false, false," +
"0, null);" +
"element.dispatchEvent(evt);" +
"}());");
答案 1 :(得分:0)
我的猜测是,您在加载文档之前正在运行executeScript调用。
要知道何时加载文档,您可以在document property或WebEngine loadworker状态属性(对于SUCCEEDED状态)添加侦听器,您可以看到loadworker解决方案的示例WebEngine javadoc。
import javafx.concurrent.Worker.State;
. . .
webEngine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
public void changed(ObservableValue ov, State oldState, State newState) {
if (newState == State.SUCCEEDED) {
// execute script here . . . .
}
}
});
webEngine.load("http://javafx.com");