1

I have a javafx application. Initially it loads a login page using WebView. Login page takes user name and redirects to another page. In this html page I have a function inside javascript. I want to call a java method while executing the script. but I end up getting an error saying

ReferenceError: Can't find variable: OpenDoc[at 17]

This my html

html>

    <body onload="login()">
        <div id="jnlpStart_EN">
            <H2>Welcome to Home Page</H2>
        </div>
    </body>

    <script type="text/javascript">
        function login() {
            OpenDoc.passDocId('q56wre');
        }
    </script>

</html>

This is my java code

public class WebEngineTest1 extends Application {

    @Override
    public void start(Stage primaryStage) {
        WebConsoleListener.setDefaultListener((webView, message, lineNumber, sourceId) -> {
            System.out.println(message + "[at " + lineNumber + "]");
        });

        WebView webView = new WebView();
        WebEngine engine = webView.getEngine();

        engine.load("http://localhost:8001/app/login");
        engine.locationProperty().addListener((obs, oldLocation, newLocation) -> {
            if (newLocation != null && newLocation.endsWith("/home")) {
                JSObject window = (JSObject) engine.executeScript("window");
                window.setMember("OpenDoc", new OpenDoc());
            }
        });
        Scene scene = new Scene(webView, 300, 150);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }

    public class OpenDoc {
        public void passDocId(String id) {
            System.out.println(id);
        }
    }
}
sparrow
  • 1,825
  • 6
  • 24
  • 35

2 Answers2

1

I have found the answer. Since after login it redirects to an URL. I had to add a listener with documentProperty(). Inside I add the code for calling java method from javascript. So while loading the page I don't get ReferenceError: Can't find variable: OpenDoc[at 17] message since I added the reference already. here is the code

engine.documentProperty().addListener((v, o, n) -> {
            String newLocation = webEngine.getLocation();
            if (newLocation != null && newLocation.endsWith("/home")) { 
                JSObject window = (JSObject) engine.executeScript("window");
                        window.setMember("OpenDoc", new OpenDoc());
            }           
        });
sparrow
  • 1,825
  • 6
  • 24
  • 35
0

First you have to enable JavaScript on the WebEngine

webEngine.setJavaScriptEnabled(true);

and this line will do the trick

webengine.executeScript("initOpenDoc(\"ID\")");
Ahmed Emad
  • 674
  • 6
  • 19