Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 420
Alaa Aref Avatar asked Feb 19 '20 14:02

Alaa Aref


People also ask

How do I get the current URL in Blazor?

Inject NavigationManager in razor. Use Uri from NavigationManager to get the current URL.

How do I redirect in Blazor?

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.

What is NavigationManager in Blazor?

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 .


1 Answers

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.

like image 198
Mu-Tsun Tsai Avatar answered Oct 13 '22 18:10

Mu-Tsun Tsai