Snippets

Victor Apoyan How To: Change input field value pragmatically in webview

Created by Victor Apoyan
// Code below set input values pragmatically in webview
// Page which is loaded in webview has following input fields:
// <input type="text" class="" name="password" id="password" autocomplete="off" maxlength="8" value="">
// <input type="text" class="" name="username" id="username" autocomplete="off" maxlength="7" value="">
// <input name="answer" type="text" style="width: 50px;background-position: -18px 0px;">

webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl("http://xxx.com/");
webView.setWebViewClient(new WebViewClient(){
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        final String password = "password";
        final String username = "username";
        final String answer = 5;

        final String js = "javascript:" +
                "document.getElementById('password').value = '" + password + "';"  +
                "document.getElementById('username').value = '" + username + "';"  +
                "var ans = document.getElementsByName('answer');"                  +
                "ans[0].value = '" + answer + "';"                                 +
                "document.getElementById('fl').click()";

        if (Build.VERSION.SDK_INT >= 19) {
            view.evaluateJavascript(js, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {

                }
            });
        } else {
            view.loadUrl(js);
        }
    }
});

Comments (0)