Valeriy Valeriy - 2 months ago 35
Android Question

programmatic click in Android WebView

Good afternoon!

I have a website with href in it which redirected me to https

<a id="mA" href="javascript:pLogin(2)" class="login-link__link private-cab-link"><i class="icon-user"></i>Авторизация</a>


So, I can click on it by javascript. It works in chrome console

javascript:(function(){document.getElementById('mA').click();})()


Now I'm trying to do the same in WebView by clicking my app's button.

public class RostelecomLoginActivity extends Activity {

WebView webView;
String url;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_rostelecom_login);
Intent webIntent = getIntent();
String url = webIntent.getStringExtra("url");

webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new MeWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSaveFormData(true);
webView.getSettings().setSavePassword(true);
webView.loadUrl(url);

Button buttoner = (Button) findViewById(R.id.button1);
buttoner.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
webView.loadUrl("javascript:(function(){document.getElementById('mA').click();})()");
}
});

}


}

I'm using MyWebViewClient to allow all certificates

public class MeWebViewClient extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}

@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}


}

The js injection doesn't work. If I click on href in WebView it works.
What can be wrong ?
Thanks.

Answer

click() isn't implemented in android js interface, you have to use HTML DOM Event Object, like this:

webView.loadUrl("javascript:(function(){"+
    "l=document.getElementById('mA');"+
    "e=document.createEvent('HTMLEvents');"+
    "e.initEvent('click',true,true);"+
    "l.dispatchEvent(e);"+
    "})()");
Comments