简体   繁体   中英

Executing a Javascript in JavaFX using WebEngine.executeScript()

I want to fill two textfields automatically and simulate a buttonclick to automatically log in to a website. I'm using the JavaFX WebView and its function .executeScript()

This is what I've got so far: (Refering to Sergey Grinevs answer on this question: Execute a Javascript function for a WebView from a JavaFX program )

        webEngine.load("websiteexample.com");
        webEngine.getLoadWorker().stateProperty().addListener(
            new ChangeListener<State>() {
                @Override
                public void changed(ObservableValue ov, State oldState, State newState) {
                   if (newState == State.SUCCEEDED) {
                        webEngine.executeScript(
                                "function login(user,pass){"
                                + " var usernameField = document.getElementById(\"username\");"
                                + " var passwordField = document.getElementById(\"password\");"
                                + " usernameField.value = user;"
                                + " passwordField.value = pass;"
                                + " var sButton = document.getElementById(\"submit\");"
                                + " sButton.click();"
                                + "}"
                                + "login('abc','123');");

                    }
                }
            });

So far this works but the Javascript will be executed in an infinite loop . I furthermore dont know why there is a Listener. Need to say that I've copied my script into the script from Sergey Grinev since that worked for me. Otherwise, by simply calling executeScript, it will throw java.lang.reflect.InvocationTargetException and many more.

How can I execute my script without a permanent loop and why does it not work without the listener?

Thanks for reading and kind regards

If I understand your question, the answer to the second part of the question, "why does it not work without the listener", is that the listener notifies you that the page has loaded. Then, it executes the code you specify when the load succeeds ( newState == State.SUCCEEDED ). So, there is a listener in order to run your code as soon as the WebEngine reports that it has loaded the page. Without the listener, you would have to choose when to run the code based on some other event, like a button click after the page loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM