How to detect idle time on web page for auto logout? #1413
-
QuestionHi All, I want to create an auto-log off sort of feature if, let's say the user is just idle on the web page for some amount of time (let's say 5 min or more). How do I know if the user is idle and start a timer based on that? I was reading about this in general on Google, and seems like in Quasar, there are ways to do this, like this discussion here Is there a way to do this through Python and NiceGUI? Basically something like once the timer hits that threshold, I can trigger some other stuff (ex: auto log off, or pop up a notification, etc.) Please let me know if there is a way to do this. Thanks a lot, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
I think it depends on what exactly you want to achieve. But something like this might be a starting point: import asyncio
import time
from nicegui import Client, background_tasks, ui
@ui.page('/')
def index(client: Client):
deadline: float = 0
def reset_deadline(duration: float = 5) -> None:
nonlocal deadline
deadline = time.time() + duration
async def auto_logoff() -> None:
reset_deadline()
while time.time() < deadline:
print(f'Time left: {deadline - time.time():.0f}')
await asyncio.sleep(1)
with client:
ui.notify('You have been logged off due to inactivity.')
background_tasks.create(auto_logoff())
ui.label('Hello World')
ui.button('Do something', on_click=reset_deadline) |
Beta Was this translation helpful? Give feedback.
background_tasks
is a (undocumented) module for running tasks in the background, i.e. if you don't want toawait
their result. This is used internally for event handling, timers etc.reset_deadline
isn't defined (to avoid registering a new callback on every page visit). So you need to re-organize the code a bit.