java代码
package main;import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import netscape.javascript.JSObject;import java.io.File;
import java.io.IOException;public class Main extends Application {@Overridepublic void start(final Stage stage) throws IOException {final WebView browser = new WebView();webEngine = browser.getEngine();String url = new File("./filePage.html").toURI().toURL().toString();webEngine.load(url);webEngine.getLoadWorker().stateProperty().addListener((ObservableValue<? extends Worker.State> ov, Worker.State oldState,Worker.State newState) -> {if (newState == Worker.State.SUCCEEDED) {JSObject win = (JSObject) webEngine.executeScript("window");win.setMember("apps",apps);//设置变量}});Button button1 = new Button("java调JS方法");button1.setOnAction(event -> {try {JSObject win = (JSObject) webEngine.executeScript("window");//webEngine.executeScript("show()");//执行js函数//win.call("show","a","b");win.eval("show('a','b')");} catch (Exception e) {e.printStackTrace();}});VBox stackPane = new VBox();stackPane.setSpacing(20);stackPane.getChildren().addAll(button1,browser);Scene scene = new Scene(stackPane,600,400);scene.setRoot(stackPane);stage.setScene(scene);stage.show();}A apps = new A();WebEngine webEngine;public static void main(String[] args) {launch(args);}//必须公有public static class A{public String showInfo(String info) {return "A{info="+ info +"}";}}
}
html代码
filePage.html
<html>
<head><meta charset="UTF-8">
</head>
<body>
<div class="top"><button onclick="showJava()">JS调java方法</button><div >JS调java方法结果:<span id="infoJava"></span></div><div >java调JS方法结果:<span id="info"></span></div>
</div>
</body>
<script>var apps = 'test';function showJava() {document.getElementById("infoJava").innerText= apps.showInfo("java");}function show(a,b) {document.getElementById("info").innerText="a="+a+",b="+b;}
</script>
</html>
运行结果