Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

javascript - programmatic click in Android WebView

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);"+
    "})()");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...