Automatic clicking an button in JavaFX Webview


Question

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>  
1
2
12/8/2013 6:36:23 PM

Accepted Answer

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.

6
5/4/2018 5:05:56 PM

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?


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon