简体   繁体   中英

Automatic clicking an button in JavaFX Webview

I am working an an JavaFX Webbrowser that can autologin to some sites, i know how to set the data to username and password fields but how to i make it execute the login button click? This is what i got so far:

String email  =  "document.getElementsByName('email')[0].value='MY_EMAIL';";
            String pass =    "document.getElementsByName('pass')[0].value='MY_PASSWORD';";
            String login =   "";
            webEngine.executeScript(email);
            webEngine.executeScript(pass);
            webEngine.executeScript(login);

and this is the javascript code of the button it should click:

<label class="uiButton uiButtonConfirm" id="loginbutton" for="u_0_c"><input value="Aanmelden" tabindex="4" type="submit" id="u_0_c"></label>  

this is a concentrated, non-specialized example... uses the dom.w3c.Node.* package

HTMLInputElement element = (HTMLInputElement)myWebView.getEngine().getDocument().getElementsByTagName("input").item(0);
element.click();

Find a way to handle the object you're looking for, and it will work.

I haven't tried that, but it should work. The idea is add jQuery to the loaded page and then to use it to click the button. This post explains how to do this with JS: How Do I Add jQuery To Head With JavaScript? So with Java it should be (I've copied the first answer into a string and executing it with the web engine):

String script = "script = document.createElement('script');\n" +
    "\n" +
    "script.onload = function() {\n" +
    "    // jQuery is available now\n" +
    "};\n" +
    "var head = document.getElementsByTagName(\"head\")[0];\n" +
    "\n" +
    "script.type = 'text/javascript';\n" +
    "script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';\n" +
    "\n" +
    "head.appendChild(script);";

webEngine.executeScript(script);

This should be done right when WebView is initialized (via webEngine.getLoadWorker().stateProperty().addListener(...) ). Note: jQuery is loaded asynchronously.

Now you should be able to click a button with jQuery:

webEngine.executeScript("$('#buttonId')[0].click()");

This post should help you with debugging JS in a WebView: JAVAFX / WebView / WebEngine FireBugLite or Some other debugger?

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