Search code examples
javaapibridgejxbrowser

JxBrowser 6.1 JavaScript Java Bridge API is not working


I think that there is a problem with the JavaScript Java Bridge API in JxBrowser 6.1 . I have tried a very simple code to call a method of a java class in Javascript. Here are the codes. In java, java is set as a property on javascript window object to an instance of Events class and then the html is loaded. In html, I simply call Close method of Events class. But when I click the Close button, java Close function doesn't get called and there is a message in console from JxBrowser saying :

Uncaught TypeError: Cannot read property 'Close' of undefined

which means that java property for window object is not defined.

Main.java:

public class Main extends Application {

    private Browser browser;

    public static void main(String[] args) {

        launch(args);

    }

    @Override
    public void start(Stage primaryStage) {

        Platform.setImplicitExit(false);

        browser = new Browser();

        JSValue window = browser.executeJavaScriptAndReturnValue("window");

        window.asObject().setProperty("java", new Events());

        BrowserView browserView = new BrowserView(browser);

        StackPane pane = new StackPane();

        pane.getChildren().add(browserView);

        Scene scene = new Scene(pane, 330, 470);

        primaryStage.initStyle(StageStyle.UNDECORATED);

        primaryStage.setScene(scene);

        primaryStage.show();

        browser.loadURL(Main.class.getResource("templates/simple.html").toExternalForm());

    }

}

class Events {

    public void Close() {

        System.out.println("close button clicked");

    }

}

simple.html:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
    <button id="Close">Close</button>
    <script>
        document.getElementById('Close').onclick = function () {
            window.java.Close();
        }
    </script>

</body>
</html>

Here is the article i've used to do this: https://jxbrowser.support.teamdev.com/support/solutions/articles/9000013062-calling-java-from-javascript

Please correct me if i'm wrong. Thanks in advance.


Solution

  • Please make sure that you load required web page before you access its JavaScript and register Java objects. For example:

    browser.addLoadListener(new LoadAdapter() {
        @Override
        public void onFinishLoadingFrame(FinishLoadingEvent event) {
            if (event.isMainFrame()) {
                Browser browser = event.getBrowser();
                JSValue value = browser.executeJavaScriptAndReturnValue("window");
                value.asObject().setProperty("Account", new Account());
            }
        }
    });
    
    browser.loadURL("form.html");