We can use NavigationManager, which has a built-in LocationChanged event that will be triggered when the user navigates away from the current page.
In the following code, we use an alert JS function by adding the IJSRuntime to show the user has navigated by overriding the OnInitialized() method through the alert message.
[Index.razor]
@page "/"
@inject NavigationManager nav
@inject IJSRuntime JSRuntime
<h1>Detect Navigation events</h1>
@code {
protected override void OnInitialized()
{
nav.LocationChanged += (o, e) =>
{
JSRuntime.InvokeVoidAsync("alert", "User has navigated to other page");
}; }}
When the user navigates from the home page to the counter page or vice versa, the alert message stating “User has navigated to other page” will be shown.
Share with