Skip to content Skip to sidebar Skip to footer

Cannot Call Javafx From Webview Javascript On Windows (virtualbox)

The following code works on Linux, but the callback does not work on Windows (VirtualBox VM). Can you please tell me why? Java: public class WebViewTest extends Application {

Solution 1:

The trick was to create the Callback as a class field:

privateCallbackcallback=newCallback ();

And then:

webEngine.load (getClass ().getResource ("WebViewTest.html").toString ());
JSObjectwindow = (JSObject) webView.getEngine ().executeScript ("window");
// BUG // window.setMember ("java", new Callback ());window.setMember ("java", callback);

Maybe there is some abusive garbage collecting on Windows? I don't know...

Solution 2:

The window object is likely replaced when a new DOM is loaded into the web engine. Try setting the callback when the document is loaded:

Callbackcallback=newCallback();
webEngine.documentProperty().addListener((obs, oldDoc, newDoc) -> {
    if (newDoc != null) {
        JSObjectwindow= (JSObject) webView.getEngine ().executeScript ("window");
        window.setMember ("java", callback);                
    }
});

(You can see that the window object changes by System.out.println(System.identityHashCode(webView.getEngine ().executeScript ("window")) before loading the HTML, and System.out.println(System.identityHashCode(window)) in the document listener.)

Solution 3:

I had a similar problem and after digging deep, I found out that you are supposed to call window.setMember ("java", new Callback ()); after rendering your html so this should work:

JSObjectwindow = (JSObject) webView.getEngine ().executeScript ("window");
webEngine.load (getClass ().getResource ("WebViewTest.html").toString ())
window.setMember ("java", newCallback ());

Also note that if you perform a reload or if you navigate to another page, you will lose your functionality again. A solid solution will be:

webEngine.documentProperty().addListener(((observable, oldValue, newValue) -> {
   if (Objects.nonNull(newValue)) {
        JSObjectwindow = (JSObject) webEngine.executeScript("window");
        window.setMember("engine", callback);
    }
}));

Post a Comment for "Cannot Call Javafx From Webview Javascript On Windows (virtualbox)"