'Blazor replace URL in browser history
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);
}
Solution 1:[1]
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.
Solution 2:[2]
The answer above didn't seem to work correctly. I got this to work with JS Interop and a simple JS function. In razor, I added this code:
JSRuntime.InvokeVoidAsync("replaceURL", url);
The url parameter must be a relative or absolute url.
I then added this JS function. You could also use pushState to add to the web history instead of replacing it.
function replaceURL(url) {
history.replaceState(null, "", url);
}
Solution 3:[3]
Starting ASP.Net Core 6.0, the NavigateTo method of NagivationManager has the overload
NavigateTo (string uri, bool forceLoad = false, bool replace = false)
where you can set the replace parameter to true to replace the current entry in the history stack.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mu-Tsun Tsai |
| Solution 2 | Mr.Technician |
| Solution 3 | d.i.joe |
