How to enter password automatically in Webview

落爺英雄遲暮 提交于 2019-12-07 10:32:57

问题


I am new to Java and Android and I got a question. I think the solution is maybe very easy but I couldn't solve it.

I created an application with a WebView the thing is I want that the webview enters username and password automatically so that the user is already logged in when he starts the application. I googled it and found something like that but it does not work

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("https://euterpe.webuntis.com/WebUntis/index.do#main");


webView.setWebViewClient(new WebViewClient ());



class MyWebViewClient extends WebViewClient {
@Override
public void onReceivedHttpAuthRequest(WebView view,
        HttpAuthHandler handler, String host, String realm) {

    handler.proceed("Username", "password");

}
}

回答1:


hello please try this:

webView.getSettings().setJavaScriptEnabled(true);

webView.loadUrl("javascript:document.getElementsByName('school').value = 'schoolname'");
webView.loadUrl("javascript:document.getElementsByName('j_username').value = 'username'");
webView.loadUrl("javascript:document.getElementsByName('j_password').value = 'password'");

webView.loadUrl("javascript:document.forms['login'].submit()");

the first line enables javascript

all other lines fill in the form and eventually submit the form.

Look at the String apostrophes please i edited my answer.




回答2:


Though this is an old question I thought I would post my solution:

    webView.getSettings().setJavaScriptEnabled(true);   

    webView.loadUrl("http://your.url");

    webView.setWebViewClient(new WebViewClient() {

        public void onPageFinished(WebView view, String url) {
            view.loadUrl("javascript:document.getElementsByName('school')[0].value = 'schoolname'");
            view.loadUrl("javascript:document.getElementsByName('j_username')[0].value = 'username'");
            view.loadUrl("javascript:document.getElementsByName('j_password')[0].value = 'password'");

            view.loadUrl("javascript:document.forms['login'].submit()");
        }
    });

It looks much alike the answer from Benjamin. Only difference is the [0] part, selecting the first found element, plus my implementation waits for the page to load before firering javascript at it.




回答3:


Replace

webView.setWebViewClient(new WebViewClient ());

with

webView.setWebViewClient(new MyWebViewClient ());

Only then the override method onReceivedHttpAuthRequest will get called.

This handling will only work for HTTP authentication requests.



来源:https://stackoverflow.com/questions/16055800/how-to-enter-password-automatically-in-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!