本文介绍了来自Javascript的WebView回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图基于(从JavaScript调用Java )。但是,当我单击WebView中的链接时,不会调用Java方法,页面也会消失。
I tried to create a simple example of callback from Javascript to Java, based on the last example in WebEngine's javadoc (Calling back to Java from JavaScript). But when I click the link in the WebView, the Java method is not called and the page disappears.
public class TestOnClick extends Application {
@Override
public void start(Stage stage) throws Exception {
try {
final WebView webView = new WebView();
final WebEngine webEngine = webView.getEngine();
Scene scene = new Scene(webView);
stage.setScene(scene);
stage.setWidth(1200);
stage.setHeight(600);
stage.show();
String webPage = "<html>\n"
+ " <body>\n"
+ " <a href=\"\" onclick=\"app.onClick()\">Click here</a>\n"
+ " </body>\n"
+ "</html>";
System.out.println(webPage);
webView.getEngine().loadContent(webPage);
JSObject window = (JSObject) webEngine.executeScript("window");
window.setMember("app", new JavaApp());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
public static class JavaApp {
public void onClick() {
System.out.println("Clicked");
}
}
}
注意:我不是使用 webView.getEngine()监视加载工作程序时,可以看到WebView中抛出的任何异常.getLoadWorker()。exceptionProperty()。addListener(...)
。
推荐答案
您正在尝试在创建之前访问webview DOM模型。
You are trying to access webview DOM model before it was created.
将 JavaApp
相关代码包装到页面加载侦听器中以实现目标:
Wrap your JavaApp
related code to the page load listener to achieve your goal:
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
@Override
public void changed(ObservableValue<? extends State> ov, State t, State t1) {
if (t1 == Worker.State.SUCCEEDED) {
JSObject window = (JSObject) webEngine.executeScript("window");
window.setMember("app", new JavaApp());
}
}
});
这篇关于来自Javascript的WebView回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!