Repository navigation
Expand file tree
/
Copy pathinactivityDetector.min.js
More file actions
1 lines (1 loc) · 2.4 KB
/
Copy pathinactivityDetector.min.js
File metadata and controls
1 lines (1 loc) · 2.4 KB
1
class InactivityDetector{constructor(e={}){this.options={warningThreshold:5,onInactivityStart:()=>{},onInactive:()=>{},onActive:()=>{},onMonitorChange:()=>{},onWindowClose:()=>{},...e},this.storageKey="inactivityDetectorHiddenTime",this.lastScreens=`${window.screen.width}x${window.screen.height}`,this.handleActivityChange=this.handleActivityChange.bind(this),this.checkMonitorChange=this.checkMonitorChange.bind(this),this.handleBeforeUnload=this.handleBeforeUnload.bind(this)}init(){localStorage.removeItem(this.storageKey),document.addEventListener("visibilitychange",this.handleActivityChange),window.addEventListener("blur",this.handleActivityChange),window.addEventListener("focus",this.handleActivityChange),window.addEventListener("beforeunload",this.handleBeforeUnload),this.monitorInterval=setInterval(this.checkMonitorChange,1e3),this.checkInitialState()}destroy(){document.removeEventListener("visibilitychange",this.handleActivityChange),window.removeEventListener("blur",this.handleActivityChange),window.removeEventListener("focus",this.handleActivityChange),window.removeEventListener("beforeunload",this.handleBeforeUnload),clearInterval(this.monitorInterval),localStorage.removeItem(this.storageKey)}checkInitialState(){const e=localStorage.getItem(this.storageKey);if(e){const t=(new Date-new Date(e))/1e3;t>=1&&(t>=this.options.warningThreshold&&this.options.onInactive("Page was hidden",Math.floor(t)),this.options.onActive(Math.floor(t))),localStorage.removeItem(this.storageKey)}}handleActivityChange(){if(document.hidden||!document.hasFocus())localStorage.getItem(this.storageKey)||(localStorage.setItem(this.storageKey,(new Date).toISOString()),this.options.onInactivityStart());else{const e=localStorage.getItem(this.storageKey);if(e){const t=(new Date-new Date(e))/1e3;if(t>=1){if(t>=this.options.warningThreshold){const e=document.hidden?"Page was hidden":"Window was blurred";this.options.onInactive(e,Math.floor(t))}this.options.onActive(Math.floor(t))}localStorage.removeItem(this.storageKey)}}}checkMonitorChange(){const e=`${window.screen.width}x${window.screen.height}`;e!==this.lastScreens&&(this.options.onMonitorChange(this.lastScreens,e),this.lastScreens=e)}handleBeforeUnload(e){const t=localStorage.getItem(this.storageKey);if(t){const e=(new Date-new Date(t))/1e3;this.options.onWindowClose(Math.floor(e))}else this.options.onWindowClose(0)}}"undefined"!=typeof window&&(window.InactivityDetector=InactivityDetector);