0

I am building a Maui Blazor app and I want to prevent the user can go back when pressing "back" button on the phone.

It is clear I can do with Maui when using xaml like this:

   protected override bool OnBackButtonPressed()
    {
        return true;
    }

How is it possible when Blazor? Didn't find any similar method to override.

  • Does this answer your question? [Disabling the Back Button in Blazor](https://stackoverflow.com/questions/60693627/disabling-the-back-button-in-blazor) – dLcreations Mar 09 '23 at 19:31
  • Gents, having asked that question (in what seems like) many years ago, I've worked on several solutions, some of which were incorporated into the NavigationManager changes that are now in Net7.0. There's a question and answer here that demonstrates how to use the new features to prevent navigation (including the back button) when an edit form is dirty. – MrC aka Shaun Curtis Mar 10 '23 at 22:47
  • https://stackoverflow.com/questions/75157902/managing-state-and-preventing-blazor-navigation-in-an-edit-form – MrC aka Shaun Curtis Mar 10 '23 at 22:48

1 Answers1

3

In the end I solved this way, introduced a flag and control when navigate away is allowed (when pressed back button the flag is not set), can navigate away only in this case when the flag is set, so the prevent is not executed.

<NavigationLock OnBeforeInternalNavigation="OnBeforeInternalNavigation"/>

@code
{
    private bool _canNavigateAway= false;

    private async Task OnBeforeInternalNavigation(LocationChangingContext context) 
    {
       if (!_canNavigateAway)
       {
          context.PreventNavigation();
       }
    }
    private void SomeMethod()
    {
        _canNavigateAway= true;
        NavigationManager.NavigateTo(route);
    }
}