返回信息流以下是我的JavaFX项目源码:
Java运行类WebViewSample:
package application;
import org.w3c.dom.Document;
import javafx.application.Application;
import javafx.concurrent.Worker;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;
public class WebViewSample extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
webEngine.getLoadWorker().stateProperty().addListener((obs, oldValue, newValue) -> {
if (newValue == Worker.State.SUCCEEDED) {
// JSObject jsobj = (JSObject) webEngine.executeScript("window");
// System.out.println(jsobj.toString());
// jsobj.setMember("ABCD", new HelloWorld());
Document doc = webEngine.getDocument();
((JSObject) doc).setMember("app", new HelloWorld());
System.out.println("+"+webEngine.executeScript("test()"));
}
});
String url = WebViewSample.class.getResource("/").toString() + "application/help.html";
webEngine.load(url);
Group root = new Group();
Scene scene = new Scene(root, 300, 250);
root.getChildren().add(webView);
primaryStage.setScene(scene);
primaryStage.show();
}
}
class HelloWorld {
public String sayGoodbye(String name) {
System.out.println("调用方法");
return "hi:" + name;
}
}
网页文件help.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h1>nihao</h1>
<button onclick="sayGoodbye('你好')">heloo</button>
<p id="my_message">是的发生</p>
<script type="text/javascript">
function sayGoodbye(name) {
document.getElementById("my_message").innerHTML = "nnn";
var message = app.sayGoodbye(name);
document.getElementById("my_message").innerHTML = message;
}
function test(){
return "test";
}
</script>
</body>
</html>
项目文件结构:
其中Main、PathSceneCreate和SceneCreate三个文件没有什么作用,是之前测试其他写的。其他文件均为项目自动生成的。
我现在在页面中点击按钮后后台前台都没有任何反应。注释掉的代码是一种方式,底下是另一种调用方式。求路过的大神给点指导,万分感谢!!!
这是一条镜像帖。来源:北邮人论坛 / java / #57229同步于 2017/8/25
Java机器人发帖
【问题】JavaFX的WebView中js调用java方法没有反应
happy3014
2017/8/25镜像同步0 回复
订阅后,新回复会通过你的通知中心匿名送达。
0 条回复
暂无回复 · 你可以订阅本帖等待新回复。