728x90
728x170

1. Blazor WebAssembly 프로젝트 추가

2. blazor-beforeunload Nuget 패키지 설치


3. Program.cs 에 아래코드 추가

builder.Services.AddBeforeUnload();


4. wwwroot의 index.html 에 스크립트 추가

<script src="_content/BlazorBeforeUnload/BeforeUnload.js"></script>


5. 화면에서 아래 처럼 사용

@page "/"

@using blazejewicz.Blazor.BeforeUnload
@using System
@implements IDisposable
@inject BeforeUnload BeforeUnload

<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

@code
{
    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";
    }
}

창 Refresh 시 BeforeUnloadHandler 이벤트로 진입합니다.
또한 BeforeUnloadHandler에서 args.CancelRequested를 true 하게 되면
아래와 같이 refresh 시 재로드 할것인지 묻는 창이 뜹니다.
(취소하게 되면 refresh 안함.)


결과

아래처럼 F5를 클릭하거나
브라우저창의 refresh 버튼을 클릭해도
Refresh 가 되기 전에 이벤트를 타는것(중단점)을 확인할수 있습니다.
Refresh 되기전에 뭔가 저장이 필요한 경우 사용하면 됩니다.

[Nuget]
https://github.com/peterblazejewicz/blazor-beforeunload

 

GitHub - peterblazejewicz/blazor-beforeunload: Blazor hook into native Window beforeunload with async/await and cancel support

Blazor hook into native Window beforeunload with async/await and cancel support - GitHub - peterblazejewicz/blazor-beforeunload: Blazor hook into native Window beforeunload with async/await and can...

github.com


[Source]
https://github.com/kei-soft/Blazor.AppTest/tree/master/Blazor.BeforeunloadTest

 

GitHub - kei-soft/Blazor.AppTest

Contribute to kei-soft/Blazor.AppTest development by creating an account on GitHub.

github.com

 

728x90
그리드형
Posted by kjun
,