Android环境下无法通过ID获取Instagram登录页元素问题求助
Hey there! Let's break down why your JavaScript isn't targeting the Instagram username field correctly in your B4A WebView setup. Here are the most common fixes to try:
1. Fix JavaScript Syntax Errors
First off, you've got a couple of typos in your JS code that are breaking it:
- It's
document.getElementById(notgetelementsByid— notice the capital E in "Element" and capital B in "ById") getElementByIdreturns a single element (since IDs are unique), so you don't need the[0]index at the end
Here's the corrected basic version of your code:
Sub EditText1_TextChanged (Old As String, NEW As String) Dim jsCode As String = $"document.getElementById('id_username').value = '${NEW}';"$ WebViewExtras1.executeJavascript(webview1, jsCode) End Sub
2. Verify the Actual Element Identifier
Instagram frequently updates its login page, so the id_username ID might no longer exist. Instead of relying on IDs (which are often dynamic), use a more stable selector like the name attribute:
- On Instagram's login page, the username input has a
name="username"attribute, which is less likely to change.
Update your JS to use querySelector instead:
Sub EditText1_TextChanged (Old As String, NEW As String) Dim jsCode As String = $"document.querySelector('input[name="username"]').value = '${NEW}';"$ WebViewExtras1.executeJavascript(webview1, jsCode) End Sub
3. Ensure the Page is Fully Loaded
If you're running the JS before the WebView finishes loading the Instagram login page, the element won't exist yet. To fix this:
- Trigger the JS code only after the page has fully loaded (use the
WebView1_PageFinishedevent) - Or add a check to confirm the element exists before trying to modify it:
Sub EditText1_TextChanged (Old As String, NEW As String) Dim jsCode As String = $" const usernameInput = document.querySelector('input[name="username"]'); if (usernameInput) { usernameInput.value = '${NEW}'; } else { console.log('Username input field not found — page might still be loading!'); } "$ WebViewExtras1.executeJavascript(webview1, jsCode) End Sub
4. Enable JavaScript in WebView
Double-check that JavaScript is enabled for your WebView in B4A. If it's disabled, your JS code won't run at all:
' Add this in your Activity_Create or WebView initialization code WebView1.JavaScriptEnabled = True
内容的提问来源于stack exchange,提问作者hshshs sghssg

