'Blazor do something after X-amount idle time

I am fairly new to blazor and core for that matter.

My issue is that i have an API Centric App that will make a login call to an api and get a JWT token. I need to find a way to log the user out after a period of Idle time and clear the JWT token which i am saving.

I read somewhere that they never added a way to detect idle time in Blazor but i am curious if anyone has a solution for this.



Solution 1:[1]

Using JavaScript onmousemove and onkeypress events to trigger the Timer function in a Razor component can identify whether a user is active or inactive. If the user has not performed any onmousemove or onkeypress events, the user is considered in an inactive state and the Timer function is called after certain TimeInterval to [perform any action that you want to do.

  1. Open _Host.cshtml and update it as below. Call the onmousemove and onkeypress properties in a JavaScript function to fire the Timer function in the Razor component.

<body>
     // . . .
     <script>
         function timeOutCall(dotnethelper) {
             document.onmousemove = resetTimeDelay;
             document.onkeypress = resetTimeDelay;
  
             function resetTimeDelay() {
                 dotnethelper.invokeMethodAsync("TimerInterval");
             }
         }
     </script>
 </body> 
  1. Now open MainLayout.razor and call the Timer method to identify whether the user is active or not. You can add your code in the method when user is found inactive
@using System.Timers
@inject IJSRuntime JSRuntime
  
 // . . .
 @code {
     private Timer timerObj;
  
     protected override async Task OnInitializedAsync()
     {
         // Set the Timer delay.
         timerObj = new Timer(7000);
         timerObj.Elapsed += UpdateTimer;
         timerObj.AutoReset = false;
         // Identify whether the user is active or inactive using onmousemove and onkeypress in JS function.
         await JSRuntime.InvokeVoidAsync("timeOutCall", DotNetObjectReference.Create(this));
     }
  
     [JSInvokable]
     public void TimerInterval()
     {
         // Resetting the Timer if the user in active state.
         timerObj.Stop();
         // Call the TimeInterval to logout when the user is inactive.
         timerObj.Start();
     }
  
     private void UpdateTimer(Object source, ElapsedEventArgs e)
     {
         InvokeAsync(async() => {

             // ======> DO WHATEVER YOU WANT TO DO HERE <======

         });
     }
 } 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SU7