What you need is a page history state manager:
For the following example I'm using Blazor Wasm but you can use this example in Blazor Server as well.
In the client app I've added this class:
PageHistoryState:
public class PageHistoryState
{
private List<string> previousPages;
public PageHistoryState()
{
previousPages = new List<string>();
}
public void AddPageToHistory(string pageName)
{
previousPages.Add(pageName);
}
public string GetGoBackPage()
{
if (previousPages.Count > 1)
{
// You add a page on initialization, so you need to return the 2nd from the last
return previousPages.ElementAt(previousPages.Count - 2);
}
// Can't go back because you didn't navigate enough
return previousPages.FirstOrDefault();
}
public bool CanGoBack()
{
return previousPages.Count > 1;
}
}
Then add this class to the services as a singleton:
builder.Services.AddSingleton<PageHistoryState>();
Inject it in your pages:
@inject WasmBlazor.Client.PageHistoryState PageHistoryState
In my markup then I've check to see if I can go back a page:
@if (PageHistoryState.CanGoBack())
{
<a href="@PageHistoryState.GetGoBackPage()">Go Back</a>
}
And I've overwritten OnInitialized()
protected override void OnInitialized()
{
PageHistoryState.AddPageToHistory("/counter");
base.OnInitialized();
}
I've done the same thing in the "fetch data" page, and I'm able to go back without the need of the JSInterop.