blazor webassembly net6.0 page inactivity

123 views Asked by At

How can i check inactivity in a page? Example: I load a page and after 60 seconds, if there is no user activity I will like to call a method.

I'm on: net6.0, web assembly,

2

There are 2 answers

0
Tom Day On

You could create some service and inject it in the MainLayout.razor (if you do not have other layouts) or App.razor (base of the application), or in the component/page that you need to be checking for this inactivity, if it does not apply to the app as a whole.

public class InactivityService
{
    private Timer inactivityTimer;
    private readonly TimeSpan inactivityDuration = TimeSpan.FromSeconds(60);
    private bool isInactive = false;

    public event Action OnInactive;

    public void Start()
    {
        inactivityTimer = new Timer(InactivityTimerCallback, null, inactivityDuration, inactivityDuration);
    }

    public void Reset()
    {
        isInactive = false;
    }

    private void InactivityTimerCallback(object state)
    {
        isInactive = true;
        OnInactive?.Invoke();
    }

    public void HandleUserActivity()
    {
        if (isInactive)
        {
            Reset();
        }
    }
}

and then use in the component:

@code {

    [Inject] InactivityService inactivityService { get; set; }

    protected override void OnInitialized()
    {
        inactivityService.OnInactive += HandleInactive;
        inactivityService.Start();
    }

    private void HandleInactive()
    {
        // Call the method you need here
    }

    protected override bool ShouldRender()
    {
        inactivityService.HandleUserActivity();
        return base.ShouldRender();
    }

    public void Dispose()
    {
        inactivityService.OnInactive -= HandleInactive;
    }
}
0
Suryateja KONDLA On

I use typescript in my blazor app instead of javascript below is ts code

namespace IdleTimeHandler {
    export class IdleTimeManager {
        private static dotnetHelper: any;
        private static timer: any;
        private static countdownElement: HTMLElement | null;
        private static DefaultTime = 1200000;// Initial time in milliseconds (20 minutes)
        private static remainingTime = IdleTimeManager.DefaultTime;

        private static initialize(dotnetHelper: any) {
            IdleTimeManager.dotnetHelper = dotnetHelper;
            IdleTimeManager.resetTimer();
            document.addEventListener("mousemove", IdleTimeManager.resetTimer);
            document.addEventListener("keypress", IdleTimeManager.resetTimer);
            document.addEventListener("click", IdleTimeManager.resetTimer);

            // Check for movement every second
            setInterval(IdleTimeManager.checkForMovement, 1000);
        }

        private static resetTimer() {
            clearTimeout(IdleTimeManager.timer);
            IdleTimeManager.remainingTime = IdleTimeManager.DefaultTime;
            IdleTimeManager.timer = setTimeout(IdleTimeManager.logout, IdleTimeManager.remainingTime);
            IdleTimeManager.updateCountdown(IdleTimeManager.remainingTime);
        }

        private static checkForMovement() {
            // Decrease remaining time by 1000 milliseconds (1 second) if no movement detected
            if (IdleTimeManager.remainingTime > 0) {
                IdleTimeManager.remainingTime -= 1000;
                IdleTimeManager.updateCountdown(IdleTimeManager.remainingTime);

                if (IdleTimeManager.remainingTime <= 0) {
                    IdleTimeManager.logout();
                }
            }
        }

        private static logout() {
            IdleTimeManager.dotnetHelper.invokeMethodAsync("LogoutMethod");
            document.removeEventListener("mousemove", IdleTimeManager.resetTimer);
            document.removeEventListener("keypress", IdleTimeManager.resetTimer);
            clearInterval(IdleTimeManager.timer);
            IdleTimeManager.updateCountdown(0);
        }

        private static updateCountdown(milliseconds: number) {
            const minutes = Math.floor(milliseconds / 60000);
            const seconds = Math.floor((milliseconds % 60000) / 1000);
            const formattedTime = `${(minutes < 10 ? "0" : "") + minutes}:${(seconds < 10 ? "0" : "") + seconds}`;
            IdleTimeManager.countdownElement = document.getElementById("countdown");
            if (IdleTimeManager.countdownElement) {
                IdleTimeManager.countdownElement.textContent = formattedTime;
            }
        }
    }
}

now using Jsintrop Pass the dotnet object

await JsRuntime.InvokeVoidAsync("IdleTimeHandler.IdleTimeManager.initialize", DotNetObjectReference.Create(this));

and call the method u want

[JSInvokable("LogoutMethod")] public void Logout() 
{

};

where u are pass this to the jsintrop the method should exist in that class