Is there a way to detect if a browser window is not currently active?

前端 未结 19 2105
无人共我
无人共我 2020-11-21 04:40

I have JavaScript that is doing activity periodically. When the user is not looking at the site (i.e., the window or tab does not have focus), it\'d be nice to not run.

19条回答
  •  囚心锁ツ
    2020-11-21 05:00

    A slightly more complicated way would be to use setInterval() to check mouse position and compare to last check. If the mouse hasn't moved in a set amount of time, the user is probably idle.

    This has the added advantage of telling if the user is idle, instead of just checking if the window is not active.

    As many people have pointed out, this is not always a good way to check whether the user or browser window is idle, as the user might not even be using the mouse or is watching a video, or similar. I am just suggesting one possible way to check for idle-ness.

提交回复
热议问题