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

Android中如何将EditText值传入WebView文本框并自动登录

How to Pass Android EditText Inputs to WebView's Login Form & Auto-Login

Got it, let's fix this issue—you're right that directly passing Java strings to JavaScript can break things because of syntax rules (like unescaped quotes). Here's a reliable, safe way to get your EditText values into the web form and trigger the login:

Step 1: Ensure JavaScript is Enabled in WebView

First, double-check you've enabled JS in your WebView settings (it's easy to overlook!):

WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Optional: Enable DOM storage if the target site requires it
webSettings.setDomStorageEnabled(true);

Step 2: Fetch EditText Values & Inject Them Safely into JavaScript

The core fix here is properly escaping your Java strings to avoid breaking JavaScript syntax. We'll use JSONObject.quote() (or JSON.stringify()) to automatically handle special characters like quotes, spaces, or symbols.

Update your onPageFinished method like this:

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

    // Get the actual input values from your EditTexts
    String userEmail = mEditTextAccount.getText().toString().trim();
    String userPassword = mEditTextPassword.getText().toString().trim();

    // Skip auto-fill if inputs are empty (optional but good practice)
    if (userEmail.isEmpty() || userPassword.isEmpty()) {
        Log.d("WebLogin", "Empty email/password, skipping auto-fill");
        return;
    }

    // Build the JavaScript code with properly escaped values
    String jsAutoLogin = String.format(
        // Declare JS variables with escaped values, then populate the form
        "var email = %s; var password = %s;" +
        "document.getElementById('m_login_email').value = email;" +
        "document.getElementById('m_login_password').value = password;" +
        // Trigger the login button (adjust the selector to match your site's button)
        "document.getElementById('login-button').click();",
        JSONObject.quote(userEmail), // Escapes the string to be JS-safe
        JSONObject.quote(userPassword)
    );

    // Execute the JS code with version compatibility
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // Use evaluateJavascript for better security and callback support
        view.evaluateJavascript(jsAutoLogin, new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String result) {
                // Optional: Handle the JS execution result
                Log.d("WebLogin", "Auto-login JS executed: " + result);
            }
        });
    } else {
        // Fallback for older Android versions
        view.loadUrl("javascript:" + jsAutoLogin);
    }
}

Key Notes to Avoid Common Issues:

  • Element Selectors: Verify that getElementById matches the actual HTML element IDs on the target site. If the form uses name instead of id, use document.getElementsByName('login_email')[0] (the [0] grabs the first matching element).
  • Special Character Handling: Using JSONObject.quote() ensures that if a user enters a password with quotes (like pass"word), it won't break the JavaScript syntax—this was almost certainly why your direct string pass failed earlier.
  • Security: Skip using addJavascriptInterface for this task (it has security vulnerabilities pre-API 17). evaluateJavascript is the recommended, safer approach for modern Android.

Troubleshooting Tip

If the form still doesn't populate, use Chrome DevTools to inspect the web page:

  1. Enable USB debugging on your device
  2. Open chrome://inspect on your computer
  3. Connect your device and inspect the WebView to confirm element IDs/selectors are correct

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:49:55