JavaFx WebView callback from Javascript failing after Garbage Collection

后端 未结 1 529
天涯浪人
天涯浪人 2020-12-11 16:18

I am currently working on a JavaFX based application, where users can interact with places that are marked on a world map. To do this, I am using an approach similiar to the

相关标签:
1条回答
  • 2020-12-11 16:56

    I solved the problem by creating an instance variable bridge in Java that holds the JavaScriptBridge instance sent to Javascript via setMember(). This way, Gargbage Collection of the instance is prevented.

    Relevant code snippet:

    public class JavaScriptBridge {
        public void callback(String data) {
            System.out.println("callback retrieved: " + data);
        }
    }
    
    private JavaScriptBridge bridge;
    
    @Override
    public void start(Stage primaryStage) throws Exception {
        WebView webView = new WebView();
        primaryStage.setScene(new Scene(new AnchorPane(webView)));
        primaryStage.show();
    
        final WebEngine webEngine = webView.getEngine();
        webEngine.load(getClass().getClassLoader().getResource("page.html").toExternalForm());
    
        bridge = new JavaScriptBridge();
        webEngine.getLoadWorker().stateProperty().addListener((observableValue, oldValue, newValue) -> {
            if (newValue == State.SUCCEEDED) {
                JSObject window = (JSObject) webEngine.executeScript("window");
                window.setMember("javaApp", bridge);
            }
        });
    
        webEngine.setOnAlert(event -> {
            System.out.println(DATE_FORMAT.format(new Date()) + " alerted: " + event.getData());
        });
    }
    

    Altough the code now works smoothly (also in conjunction with Leaflet), I am still irritated of this unexpected behaviour...

    Edit: The explanation for this behaviour is documented since Java 9 (thanks @dsh for your clarifying comment! I was working with Java 8 at the time and unfortunately didn't have this information at hand...)

    0 讨论(0)
提交回复
热议问题