androidandroid-webviewandroid-websettings

Android -- Prevent Webpage from Focusing on Form


I've a simple WebView, but the problem I'm having is that the when a page loads Android automatically focuses on the first text field in a form.

In other words, when the webpage loads, Android shows a cursor in the first text field, which hides the placeholder text.

How can I prevent this behavior??


Solution

  • I managed to prevent the momentary overlay shift by setting outline: none on my input element.

    I got the wild page scrolling and disappearing keyboard to settle down by setting overflow: hidden on the html body when showing the dialog, and then removing it again when hiding the dialog. This has a nasty side effect of resetting the page's scroll position, so I save it and restore it as necessary, and wrap all this hackery in conditionals so it only runs on Android. (I hope my Android users won't be too distracted when they see the page contents change beneath the semi-transparent overlay while the dialog is open.)

    Interestingly, I was also able to prevent the wild page scrolling by catching the touchstart event on my overlay element and calling preventDefault(). This makes me wonder if all this madness was caused by a sequence of events like this:

    touchstart bubbles up to the document root browser sees touchstart where the duplicate input field was placed browser gives focus to the input field soft keyboard appears to allow typing in the input field viewport gets resized to accommodate the soft keyboard resized viewport during touch event looks like a touch drag to the browser spurious drag causes the page to scroll and dismisses the keyboard I didn't end up catching touchstart to solve the problem, because it prevented the input field from gaining focus, and calling focus() from javascript just didn't work. I have read that the Android browser disables the focus() method on input fields, which would explain this behavior. Perhaps it does this because it wouldn't work with the duplicate text widgets it creates over the html-defined fields.