Rohit
Rohit

Reputation: 810

Click button automatically in webview?

I created an app with Webview and need to press button automatically

Use case:- open link web link and want to press "Login Here" button automatically (Second button at right).

I tried Using this:-

Html from website for "Login Here" button was <input _ngcontent-c13="" style="padding: 2px" type="button" class="pri_btn" value="Login Here"> It does not have id or name so i tried with class name but nothing happened

String js = "javascript:(function(){"+
    "l=document.getElementByClassName('pri_btn');"+
    "e=document.createEvent('HTMLEvents');"+
    "e.initEvent('click',true,true);"+
    "l.dispatchEvent(e);"+
    "})()";
    webView.evaluateJavascript(js, new ValueCallback<String>() {
        @Override
        public void onReceiveValue(String s) {
            String result = s;

        }
    });

which return null.

Any help will be appreciated!

Upvotes: 1

Views: 3549

Answers (2)

michal3377
michal3377

Reputation: 1462

You probably wanted to use a method called getElementsByClassName (note the plural) which returns array of elements. So your code should look like this:

String js = "javascript:(function(){"+
    "l=document.getElementsByClassName('pri_btn')[0];"+
    "l.click();"+
    "})()";
webView.evaluateJavascript(js, new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String s) {
        String result = s;
    }
});

Also, when I tried running this function, an SSL error occured during the redirect. To fix this you should override onReceivedSslError() method in your WebViewClient, like this:

webView.setWebViewClient(new WebViewClient(){
    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        if (handler != null){
            handler.proceed();
        } else {
            super.onReceivedSslError(view, null, error);
        }
    }
});

webView.getSettings().setDomStorageEnabled(true);

Edit: Checking for "login" occurence in the elements' value:

javascript:(function(){
tab = document.getElementsByClassName('pri_btn');
for(var i=0; i< tab.length; i++){
    if(tab[i].value.toLowerCase().indexOf("login") !== -1) return tab[i].click();
}
})()

Upvotes: 3

Indrajith
Indrajith

Reputation: 900

there is no method called getElementByClassName. It should be getElementsByClassName. Also getElementsByClassName returns an array not a DOM element. So you can't use variable l as an element.

Try This:

var loginBtns=document.getElementByClassName('pri_btn');
//assuming that there is only one element with class name pri_btn
loginBtns[0].click();

Upvotes: 0

Related Questions