Search code examples
c#xamarin.android

Webview show device keyboard on touch and ignore website focus script


I am loading an external website using WebView.

The problem I am facing is that the website got some javascript code which focus different input fields on the website. The device keyboard keeps showing whenever you start the application or when the websites reloads (which happens from time to time).

Is there any way to stop/block any javascript xx.focus(); code? Or can you somehow in webview only make the keyboard visible when pressing any input field?


Solution

  • My solution was to add/inject a custom javascript to the website.

    Not the best solution, but it is working for the website. If anyone finds a solution that's better than this, feel free to post it and I'll mark that as a Answer.

        protected override void OnCreate(Bundle savedInstanceState)
        {
            // ... //
    
            // Iniate webview
            WebView web_view = new WebView(this);
            web_view = FindViewById<WebView>(Resource.Id.webview);
            web_view.Settings.JavaScriptEnabled = true;
            web_view.Settings.DomStorageEnabled = true;
            // Create custom WebViewClient to override
            web_view.SetWebViewClient(new WebViewOverride(this));
    
            web_view.LoadUrl(url);
        }
    

    Whenever the page finished loading I'll start with a blur to remove focus from the input fields that could have been added on page load. I'll add a click eventlistener, which checks if the clicked element isn't a type of "input". If not a input field - remove focus (the reason for this is that the input field gets focused sometime when you press different buttons).

    public class WebViewOverride : WebViewClient
    {
        public override void OnPageFinished(WebView view, String url)
        {
            view.LoadUrl("javascript:  (function () { " +
                "document.activeElement.blur(); " +
                "var container = document.getElementById('UpdatePanel'); " +
                "container.addEventListener('click', function(e) { " +
                "var input = e.target.nodeName.toLowerCase(); " +
                "if (input !== 'input') { document.activeElement.blur();  } " +
                "}); " +
                "})();");
        }
    }