Blazor hook into native Window beforeunload with async/await and cancel support
In your startup configuration configure DI:
public void ConfigureServices(IServiceCollection services)
{
services.AddBeforeUnload();
}
In your client pages use the instance via dependency injection:
@page "/counter"
@using blazejewicz.Blazor.BeforeUnload
@using System
@implements IDisposable
@inject BeforeUnload BeforeUnload
protected override void OnInitialized()
{
BeforeUnload.BeforeUnloadHandler += BeforeUnloadHandler;
}
public void Dispose()
{
BeforeUnload.BeforeUnloadHandler -= BeforeUnloadHandler;
}
void BeforeUnloadHandler(object sender, BeforeUnloadArgs args)
{
args.CancelRequested = true;
args.ReturnValue = "Please save your data";
}
@peterblazejewicz