Android中如何将EditText值传入WebView文本框并自动登录
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
getElementByIdmatches the actual HTML element IDs on the target site. If the form usesnameinstead ofid, usedocument.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 (likepass"word), it won't break the JavaScript syntax—this was almost certainly why your direct string pass failed earlier. - Security: Skip using
addJavascriptInterfacefor this task (it has security vulnerabilities pre-API 17).evaluateJavascriptis the recommended, safer approach for modern Android.
Troubleshooting Tip
If the form still doesn't populate, use Chrome DevTools to inspect the web page:
- Enable USB debugging on your device
- Open
chrome://inspecton your computer - Connect your device and inspect the WebView to confirm element IDs/selectors are correct
内容的提问来源于stack exchange,提问作者user11715585

