如何让Android webview记住用户名和密码?

时间:2015-08-03 17:51:57

标签: android webview remember-me

此处使用Android Studio中的代码。我还添加了Android Studio代码下面的html代码,使用javascript记住cookie中的用户名和密码。它只适用于某些Android设备。我不知道为什么。我想让它适用于所有Android设备。 希望这将是一个简单的方法。请帮忙。 我希望用户输入他的用户名/密码一次,应该在下次访问时填写。

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Go To Our Facebook Page");

        WebView myWebView = (WebView) findViewById(R.id.webview);
        myWebView.setWebViewClient(new WebViewClient());
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("http://www.hksalonjob.comslogin.php");

    }

这里使用html代码,使用javascript记住用户名和密码。

    <!DOCTYPE HTML>

    <html>
        <head>
            <title>Salon Job HK</title>
            <meta http-equiv="content-type" content="text/html; charset=utf-8" />
            <meta name="description" content="" />
            <meta name="keywords" content="" />
            <!--[if lte IE 8]><script src="css/ie/html5shiv.js"></script><![endif]-->
            <script src="js/jquery.min.js"></script>
            <script src="js/jquery.scrolly.min.js"></script>
            <script src="js/jquery.dropotron.min.js"></script>
            <script src="js/jquery.scrollex.min.js"></script>
            <script src="js/skel.min.js"></script>
            <script src="js/skel-layers.min.js"></script>
            <script src="js/init.js"></script>
            <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
            <noscript>
                <link rel="stylesheet" href="css/skel.css" />
                <link rel="stylesheet" href="css/style.css" />
                <link rel="stylesheet" href="css/style-xlarge.css" />
            </noscript>
            <!--[if lte IE 9]><link rel="stylesheet" href="css/ie/v9.css" /><![endif]-->
            <!--[if lte IE 8]><link rel="stylesheet" href="css/ie/v8.css" /><![endif]-->

        </head>
        <body>

            <!-- Header -->


            <!-- Main -->



        <div id="main" class="wrapper style1">
        <div class="container">


          <form ACTION="<?php echo $loginFormAction; ?>" name="form1" method="POST">



                                        <div class="12u$">
                                          <input type="tel" name="tel" required id="tel"  pattern="[0-9]{1}[0-9]{7}"  maxlength="8" value="" placeholder="phone number"/>
                                        </div>
                                        <br>

                                        <div class="12u$">
                                          <input type="password" name="spassword" required id="spassword"  maxlength="8" placeholder="" />
                                        </div>

                                        <br>
                                        <div class="12u$">
                                        <input type="checkbox" name="sremember" id="sremember" />
                                        <label for="sremember">Remember me</label>

                                        </div>


                          <INPUT Type="submit" class="button special fit" name="Login" id="Login" value="login">

            </form>  


            <script>
            //remember username and password
                        $(function() {

                            if (localStorage.chkbx && localStorage.chkbx != '') {
                                $('#sremember').attr('checked', 'checked');
                                $('#tel').val(localStorage.tel);
                                $('#spassword').val(localStorage.spassword);
                            } else {
                                $('#sremember').removeAttr('checked');
                                $('#tel').val('');
                                $('#spassword').val('');
                            }

                            $('#sremember').click(function() {

                                if ($('#sremember').is(':checked')) {
                                    // save username and password
                                    localStorage.tel = $('#tel').val();
                                    localStorage.spassword = $('#spassword').val();
                                    localStorage.chkbx = $('#sremember').val();
                                } else {
                                    localStorage.tel = '';
                                    localStorage.spassword = '';
                                    localStorage.chkbx = '';
                                }
                            });
                        });

            </script>

        </div>
        </div>

    </body>
    </html>

1 个答案:

答案 0 :(得分:4)

请检查webview是否存储Cookie,例如像这样:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("Go To Our Facebook Page");

    //not sure if you need this
    CookieSyncManager.createInstance(this;
    //it is default true, but hey... 
    CookieManager.getInstance().setAcceptCookie(true);

    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.setWebViewClient(new WebViewClient() {

    @Override
    public void onPageFinished(WebView view, String url) {

        //Do you have cookies?
        Log.d("Cookie", "url: " + url + ", cookies: " + CookieManager.getInstance().getCookie(url)); 
    }

    });
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.loadUrl("http://www.hksalonjob.comslogin.php");

}

编辑:好的,忘记上面的行: - )

小心,我在这里写的不是安全感知的好习惯。 我只向您展示它基本上如何工作(完全未经测试)。

您可以使用JavascriptInterface在Java和Javascript之间交换数据:

在Java中:

 @Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("Go To Our Facebook Page");


    WebView myWebView = (WebView) findViewById(R.id.webview);
    myWebView.setWebViewClient(new WebViewClient() {

    @Override
    public void onPageFinished(WebView view, String url) {

        //Is the url the login-page?
        if (url.equals ("http://www.hksalonjob.comslogin.php") == true) {

             //load javascript to set the values to input fields
             SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
             String usr= prefs.getString("usr", null);
             String pwd= prefs.getString("pwd", null);
             if (usr== null || pwd == null) {
                 //we  have no values - leave input fields blank
                 return;
             }
             view.loadUrl("javascript:fillValues(" + usr + "," + pwd + ");");
        } 
    }

    });

    myWebView.addJavascriptInterface(new JavaScriptInterface(), "Android");
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.loadUrl("http://www.hksalonjob.comslogin.php");

}


private class JavaScriptInterface {

    /**
    * this should be triggered when user and pwd is correct, maybe after
    * successful login
    */
    public void saveValues (String usr, String pwd) {

      if (usr == null || pwd == null) {
           return;
      }

      //save the values in SharedPrefs
      SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
      editor.putString("usr", usr);
      editor.putString("pwd", pwd);
      editor.apply();
    } 
}

在Javascript中:

//trigger this after successful login
function afterSuccessLogin(usr, pwd) {

    if (Android != undefined) {
        if (Android.saveValues != undefined) {

            Android.saveValues(usr, pwd);  
        }
    }       
}
// this will be triggered by webview 
function fillValues(usr, pwd) {

    //fill input fields with values       
}