4

In a Blazor based SPA, you must be able to stop the user navigating back using the back button in the browser. However, I can't find any information about how to do this.

In classic ASPX this was relatively simple, but how do you do it on a Blazor Application/Page? I've seen [NoCache] on Views, but that doesn't seem to apply to Blazor pages/components. The javascript window.history.forward() option sort of works, but it refreshes the page, and thus loses the form changes.

MrC aka Shaun Curtis
  • 19,075
  • 3
  • 13
  • 31

3 Answers3

4

Cancelling the navigation is not yet supported. See github issues :

.Net 7 Update

Since .Net 7 you can use NavigationManager.RegisterLocationChangingHandler with LocationChangingContext.PreventNavigation :

NavigationManager.RegisterLocationChangingHandler(async context =>
{
    if (!EditContext.IsModified())
    {
        return;
    }

    var isConfirmed = await JSRuntime.InvokeAsync<bool>("window.confirm", Localizer["Are you sure you want to leave this page?"]?.ToString())
        .ConfigureAwait(false);

    if (!isConfirmed)
    {
        context.PreventNavigation();
    }
});
agua from mars
  • 16,428
  • 4
  • 61
  • 70
2

I'm providing an answer to this question because it gets a lot of views: that suggests a lot of people are searching for an answer to the question.

Since I first asked the question I've worked on various solutions. There's no perfect solution, but I've put together a Gist here. The solution is far too big for a StackOverflow answer.

MrC aka Shaun Curtis
  • 19,075
  • 3
  • 13
  • 31
1

in Net7.0 this issue has been resolved by adding the new Navigation manager features. There's an a question and answer here that demonstrates how to use the features in an edit form. - Managing State and Preventing Blazor Navigation in an Edit Form

MrC aka Shaun Curtis
  • 19,075
  • 3
  • 13
  • 31