javascriptandroidmauimaui-blazor

Unable to programatically element.focus() a textarea/input in .net maui blazor


I am having problem trying to auto focus a textarea/input tag using .NET MAUI Blazor when a page is loaded. Happens only on Android but iOS is working fine. And it does not showing any error at all. Just nothing happen.

here are my codes:

<input type="text" @ref="myref" />
<script>
    window.exampleJsFunctions =
    {
        focusElement: function (element) {
            element.focus();
        }
    };
</script>
private ElementReference myref;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", myref);
    }
}

Solution

  • I can reproduce your problem if this razor page is the root page in your project. This is because the webview is not focused now. So you can make the BlazorWebview focused at first.

    The easiest way is call the Focus() method:

    In the xaml:

    <BlazorWebView x:Name=blazorWebView/>
    

    And in the Page's code behind:

         protected override void OnHandlerChanged()
         {
             base.OnHandlerChanged();
             blazorWebView.Focus();
         }
    

    But this will not show the soft keyboard. So I call the native code to force to show it.

    In the code behind:

    public partial class MainPage : ContentPage
     {
         public BlazorWebView BlazorWebView;
         public MainPage()
         {
             InitializeComponent();
             BlazorWebView = blazorWebView;
         }
     }
    

    And in the razor page:

    protected override async Task OnAfterRenderAsync(bool firstRender)
        {
    #if ANDROID
            var webview = (App.Current.MainPage as MainPage).BlazorWebView.Handler.PlatformView as Android.Webkit.WebView;
            webview.Focusable = true;
            webview.RequestFocus(Android.Views.FocusSearchDirection.Down);
            Android.Views.InputMethods.InputMethodManager inputManager = (Android.Views.InputMethods.InputMethodManager)(Microsoft.Maui.ApplicationModel.Platform.CurrentActivity).GetSystemService(Android.App.Application.InputMethodService);
            inputManager.ShowSoftInput(webview, Android.Views.InputMethods.ShowFlags.Forced);
            //inputManager.ToggleSoftInput(Android.Views.InputMethods.InputMethodManager.ShowForced, Android.Views.InputMethods.HideSoftInputFlags.ImplicitOnly);
            webview.PerformClick();
    #endif
            if (firstRender)
            {
                await JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", myref);
            }
        }