You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android WebView中保存用户名和密码登录凭据的实现方案咨询

解决WebView保存登录状态的问题

Hey there! Totally get where you’re coming from—saving login state in a WebView can feel tricky when the old setSavePassword method is deprecated. Let’s walk through a few practical, modern approaches you can integrate into your app, using your existing code as a starting point.

方法1:利用WebView的Cookie自动管理(最简单的方案)

Most websites use cookies to maintain login sessions, and WebView can handle this automatically with a few configuration tweaks. You don’t even need to manually store usernames/passwords—just let the WebView persist session cookies.

Here’s how to update your onCreate method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mywebView = findViewById(R.id.webview);
    mywebView.setWebViewClient(new mywebClient()); // 注意对应你定义的WebViewClient子类

    // 配置Cookie管理,允许持久化会话
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        cookieManager.setAcceptThirdPartyCookies(mywebView, true);
        // 启用DOM存储,部分网站依赖该特性保存会话状态
        mywebView.getSettings().setDomStorageEnabled(true);
    }

    WebSettings webSettings = mywebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    // 启用WebView内置表单保存(替代废弃的setSavePassword)
    webSettings.setSaveFormData(true);
    webSettings.setSavePassword(false); // 废弃方法直接设为false即可

    mywebView.loadUrl("你的目标网站URL");
}

With this setup, the WebView will remember the user’s session cookie just like a regular browser—so they won’t have to re-login every time they open the app.

方法2:使用Android Autofill Framework(官方推荐)

If you want to let users explicitly save their username/password (and have it autofill across apps), the Android Autofill Framework is the way to go. It’s built into the system, secure, and aligns with user expectations.

To enable it for your WebView:

  • Ensure your app’s target SDK is at least 26 (Autofill was introduced in API 26)
  • Add this setting to your WebView’s WebSettings:
webSettings.setAutofillEnabled(true);

Modern WebViews will automatically detect standard login forms and prompt users to save credentials via the system’s Autofill UI. No extra code for form detection is needed—it works out of the box for most login pages.

方法3:自定义JS注入 + EncryptedSharedPreferences(完全控制)

If you need full control (like storing credentials to use across other parts of your app), you can use JavaScript to extract form data, encrypt it, and save it to EncryptedSharedPreferences—never store plaintext passwords!

Step 1: Save credentials when user submits the login form

Update your mywebClient class to inject JS after the login page loads:

@Override
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    // 检查是否是登录页面(替换为你的登录页URL特征)
    if (url.contains("login")) {
        // 注入JS监听表单提交事件,获取用户名和密码
        view.evaluateJavascript(
            "document.querySelector('form').addEventListener('submit', function(e) {" +
                "var username = document.getElementById('username').value;" + // 替换为你的用户名输入框ID
                "var password = document.getElementById('password').value;" + // 替换为你的密码输入框ID
                "window.android.saveCredentials(username, password);" +
            "});",
            null
        );
    }
}

Step 2: Create a JavaScript interface to pass data to Android

Add this inner class to your MainActivity:

public class WebAppInterface {
    @JavascriptInterface
    public void saveCredentials(String username, String password) {
        // 使用EncryptedSharedPreferences加密保存(禁止用普通SharedPreferences!)
        try {
            EncryptedSharedPreferences sharedPreferences = EncryptedSharedPreferences.create(
                "LoginPrefs",
                MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC),
                getApplicationContext(),
                EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
            );
            sharedPreferences.edit()
                .putString("username", username)
                .putString("password", password)
                .apply();
        } catch (GeneralSecurityException | IOException e) {
            e.printStackTrace();
        }
    }
}

Then register this interface in your onCreate method:

mywebView.addJavascriptInterface(new WebAppInterface(), "android");

Step 3: Autofill credentials on app launch

When the login page loads again, inject JS to fill the saved credentials:

@Override
public void onPageFinished(WebView view, String url) {
    super.onPageFinished(view, url);
    if (url.contains("login")) {
        // 从EncryptedSharedPreferences读取保存的凭证
        EncryptedSharedPreferences sharedPreferences = /* 初始化代码同上 */;
        String savedUsername = sharedPreferences.getString("username", "");
        String savedPassword = sharedPreferences.getString("password", "");

        if (!savedUsername.isEmpty() && !savedPassword.isEmpty()) {
            // 注入JS填充表单
            view.evaluateJavascript(
                "document.getElementById('username').value = '" + savedUsername + "';" +
                "document.getElementById('password').value = '" + savedPassword + "';",
                null
            );
        }
    }
}

Critical Security Note

To use EncryptedSharedPreferences, add the Jetpack Security library to your app’s build.gradle file:

dependencies {
    implementation "androidx.security:security-crypto:1.1.0-alpha06"
}

Final Tips

  • Use HTTPS: Ensure your target website uses HTTPS to prevent credential sniffing
  • Handle session expiration: Even with cookies, sessions can expire—add logic to detect when the user is logged out and prompt re-authentication
  • Robust selectors: Avoid hardcoding element IDs; use more flexible selectors like input[type='email'] or input[type='password'] to avoid breakage if the website updates its form structure

Hope these solutions help you get login persistence working smoothly! 🚀

内容的提问来源于stack exchange,提问作者Naman Tomar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 10:52:33