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,
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,
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;
}
}