'Showing soft keyboard when autofocusing on a text input does not work without user interaction
I want to autofocus on a text field and show the soft keyboard when I load my page in the android system webview. Unfortunately, it appears that the soft keyboard never shows up unless I explicitly click a button that calls input.focus().
I'm using androidx.webkit:webkit:1.4.0 and can reproduce the issue on an emulator as well as a physical device using this minimal sample app: https://github.com/dsyang/android-webview-auto-soft-keyboard-bug
In the sample app, I load the webview url like this:
/* MainActivity.kt */
...
// Load the content
binding.webview.loadUrl("......./index.html")
binding.webview.requestFocus()
...
override fun onPageFinished(view: WebView?, url: String?) {
val webView = view ?: return
webView.requestFocus()
webView.evaluateJavascript("""
onPageFinished()
""".trimIndent(), null)
}
The html and javascript look like this:
/* index.html */
<body>
<input type="text" id="focusme" placeholder="Auto focus and show soft keyboard" />
<button class="button" onclick="focusToShowSoftKeyboard()" type="button" value="Focus">Focus #focusme</button>
</body>
/* main.js */
function focusToShowSoftKeyboard() {
console.log("I am about to focus the following element: ", document.getElementById("focusme"));
document.getElementById("focusme").focus();
console.log("details", {
activeElement: document.activeElement,
hasFocus: document.hasFocus(),
focusMe: document.getElementById("focusme")
})
}
function onPageFinished() {
console.log("onPageFinished")
setTimeout(() => {
console.log("focusing to show keyboard")
focusToShowSoftKeyboard()
}, 1000)
}
There's a video of the sample app in action in the repo (link: https://user-images.githubusercontent.com/529969/169964147-665722e7-58a1-4c55-baa5-b231d6a87f43.mp4). You can see that the input field focuses on page load but it doesn't show the soft keyboard unless I focus it with the button.
What do I need to do so that I can focus on the input field and get the soft keyboard to show up on page load?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
