JavaFX中WebView的java与JS代码互相调用

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 {
    @Override
    public 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 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


    


JS调java方法结果:
java调JS方法结果:

运行结果

JavaFX中WebView的java与JS代码互相调用_第1张图片

你可能感兴趣的:(javafx)