8

Question:

Is there a way on Blazor to cancel navigation?

Let's supose a siple a href like this:

<a href="/some/other/blazor/spa/page">Go</a>

I would like to cancel navigation (for example if we are editing a form)

What I have tried.

Via JS

I set onbeforeunload dom delegate via JSInterop:

window.onbeforeunload = function(){
        return 'Vols abandonar aquesta pàgina?';
      };

but blazor bypass it.

Via locationchanged

I tried unsuccessfully to intercept navigation on locationchanged event:

@implements IDisposable
@inject NavigationManager NavigationManager

...

protected override void OnInitialized()
{
    NavigationManager.LocationChanged += HandleLocationChanged;
}

private void HandleLocationChanged(object sender, LocationChangedEventArgs e)
{
    // Cancel Navigation Here
}

public void Dispose()
{
    NavigationManager.LocationChanged -= HandleLocationChanged;
}
Ogglas
  • 62,132
  • 37
  • 328
  • 418
dani herrera
  • 48,760
  • 8
  • 117
  • 177

4 Answers4

5

Currently no, this feature is being discussed for .NET V5 - and has a community contribution pull-request so hopefully will make it in. https://github.com/dotnet/aspnetcore/pull/24417

The page is not changed when you navigate in Blazor, so there is no unload in order to trigger onbeforeunload.

Peter Morris
  • 20,174
  • 9
  • 81
  • 146
3

This functionality was added in .NET 7, the documentation can be found in the 'Handle/prevent location changes' section of the 'Routing and navigation' page.

tomRedox
  • 28,092
  • 24
  • 117
  • 154
1

Update to @PeterMorris answer.

As of 2021-05-17 a location changing event for NavigationManger is now committed for .NET 6.0. I hope it will be possible to catch this event on a global level in the application.

enter image description here

https://github.com/dotnet/aspnetcore/issues/14962

Ogglas
  • 62,132
  • 37
  • 328
  • 418
-2

have you tried to put your js file in the index.html or _host.cshtml page ?

raphadesa
  • 349
  • 1
  • 5
  • 11