How to detect idle time in JavaScript elegantly?

前端 未结 30 2347
别跟我提以往
别跟我提以往 2020-11-21 11:51

Is it possible to detect \"idle\" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.

Idle time:

30条回答
  •  悲&欢浪女
    2020-11-21 12:53

    (Partially inspired by the good core logic of Equiman earlier in this thread.)

    sessionExpiration.js


    sessionExpiration.js is lightweight yet effective and customizable. Once implemented, use in just one row:

    sessionExpiration(idleMinutes, warningMinutes, logoutUrl);
    
    • Affects all tabs of the browser, not just one.
    • Written in pure JavaScript, with no dependencies. Fully client side.
    • (If so wanted.) Has warning banner and countdown clock, that is cancelled by user interaction.
    • Simply include the sessionExpiration.js, and call the function, with arguments [1] number of idle minutes (across all tabs) until user is logged out, [2] number of idle minutes until warning and countdown is displayed, and [3] logout url.
    • Put the CSS in your stylesheet. Customize it if you like. (Or skip and delete banner if you don't want it.)
    • If you do want the warning banner however, then you must put an empty div with ID sessExpirDiv on your page (a suggestion is putting it in the footer).
    • Now the user will be logged out automatically if all tabs have been inactive for the given duration.
    • Optional: You may provide a fourth argument (URL serverRefresh) to the function, so that a server side session timer is also refreshed when you interact with the page.

    This is an example of what it looks like in action, if you don't change the CSS.

提交回复
热议问题