ef2011
ef2011

Reputation: 10631

How to Programmatically Enter form input fields in WebView, then click submit?

I don't have any problem parsing WebView HTML or loading URLs (relative or absolute) but I am stumped as to how to programmatically "simulate" the user entering username & password, then clicking the submit/login button, given the following HTML:

<form method="post" class="mobile-login-form" id="login_form" action="https://www.example.com/login.php?m=m&amp;refsrc=http%3A%2F%2Fm.example.com%2F&amp;refid=0">
  <input type="hidden" name="lsd" autocomplete="off">
  <input type="hidden" name="post_form_id" value="1b3cf017c90d483cc50fcac3f2a9a283">
  <input type="hidden" name="charset_test" value="€,´,€,´,?,?,?">
  <input type="hidden" name="version" value="1">
  <input type="hidden" id="ajax" name="ajax" value="1">
  <input type="hidden" id="width" name="width" value="313">
  <input type="hidden" id="pxr" name="pxr" value="1.5">
  <input type="hidden" id="gps" name="gps" value="1">
  <div class="bgx msf" data-sigil="intfs">
    <div class="mfss fcg">Username:
    </div>
    <input class="input mobile-login-field" name="username" value="" type="text">
  </div>
  <div class="bgx msf" data-sigil="intfs">
    <div class="mfss fcg">Password:
    </div>
    <input class="input mobile-login-field" autocorrect="off" autocapitalize="off" name="pass" type="password">
  </div>
  <div class="bgx msf" data-sigil="intfs">
    <label class="btn btnC touchable" data-sigil="blocking-touchable">
      <input type="submit" value="Log In" class="mfss" name="login">
    </label>
  </div>
</form>

(I don't control that HTML, this is just an example for an arbitrary website prompt)

I don't need to do so called "silent authentication" - I merely want to provide a convenience shortcut for the user clicking a button instead of re-typing username & password over and over again (in case, clear cache or clear data were performed).

Upvotes: 2

Views: 1608

Answers (2)

bitle
bitle

Reputation: 415

Define JS function within your html page and call it with following method.

 private void callJavaScriptFunction(String functionName, List<String> params) {
            String javaScript = "javascript:";

        javaScript += functionName + " ( ";

        if (params != null) {
                for(int i = 0; i < params.size(); i++) {
                        javaScript += params.get(i);

                        if (i != params.size() - 1) {
                                javaScript += ", ";
                        }
                }
        }

        javaScript += ");";

        Log.d(javaScript);

        webView.loadUrl(javaScript);
}

Upvotes: 0

Ron
Ron

Reputation: 24235

Have you tried using monkey tools. Should be able to do that task.

Upvotes: 1

Related Questions