Is there a way in Blazor routing to replace the URL link when navigating to another page? Something similar to window.location.replace in JS, or the replace attribute in React's "Link" tag, or React's history.replace? I don't want to have a history item with every navigation in the application..
Update: I tried the following in the index page, but no avail:
@inject IJSRuntime js
@inject NavigationManager NavigationManager
protected override void OnInitialized()
{
NavigationManager.LocationChanged += LocationChanged;
base.OnInitialized();
}
private void LocationChanged(object sender, LocationChangedEventArgs e)
{
js.InvokeVoidAsync("replace", e.Location);
}
And the js function is:
function replace(url) {
window.location.replace(url);
}
Inject NavigationManager in razor. Use Uri from NavigationManager to get the current URL.
You can redirect to a page in Blazor using the Navigation Manager's NavigateTo method. In the following code snippet, it will redirect to the home page when this page gets loaded. Similarly, you can call NavigateTo() method from NavigationManager class anywhere to redirect to another page.
Access to browser navigation from Blazor is provided via the NavigationManager service. This can be injected into a Blazor component using @inject in a razor file, or the [Inject] attribute in a CS file. The NavigationManager service has two members that are of particular interest; NavigateTo and LocationChanged .
This feature is actually provided in the JS interop, but somehow not in the NavigationManager
as of the writing of this answer. So what you need to do is to directly invoke the JS function:
js.InvokeVoidAsync("Blazor._internal.navigationManager.navigateTo", yourReletiveUrl, false, true);
Here the third parameter specifies that it should replace the history instead of pushing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With