navigationblazorsingle-page-applicationblazor-server-side

Can I prevent navigation in Blazor?


In Blazor Server Side app, is there some javascript involved that performs the actual navigation, e.g. when user clicks a link? I mean something like window.history.pushState(..).

Is it theoretically possible to override that javascript to prevent navigation under some circumstances (when there are unsaved changed on the page, etc.)?


Solution

  • Since .NET 7 there is a NavigationLock in the Microsoft.AspNetCore.Components.Routing namespace. (https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.routing.navigationlock?view=aspnetcore-7.0)

    That component will enable you to react on an internal routing event (to a routed component) and to an external event (e.g. someone types www.google.com in the address bar).

    More information and examples here: https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-7.0