Last active
January 19, 2022 11:01
-
-
Save jasonheecs/5f7efd8a62719da344ae23f7a62cfa9c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let heartBeatActivated = false; | |
class HeartBeat { | |
constructor() { | |
document.addEventListener('DOMContentLoaded', () => { | |
this.initHeartBeat(); | |
}); | |
} | |
initHeartBeat() { | |
this.lastActive = new Date().valueOf(); | |
if (!heartBeatActivated) { | |
['mousemove', 'scroll', 'click', 'keydown'].forEach((activity) => { | |
document.addEventListener(activity, (ev) => { | |
this.lastActive = ev.timeStamp + performance.timing.navigationStart; | |
}, false); | |
}); | |
heartBeatActivated = true; | |
} | |
} | |
} | |
window.heartBeat = new HeartBeat(); | |
const sessionTimeoutPollFrequency = 5; | |
function pollForSessionTimeout() { | |
if ((Date.now() - window.heartBeat.lastActive) < (sessionTimeoutPollFrequency * 1000)) { | |
return; | |
} | |
let request = new XMLHttpRequest(); | |
request.onload = function (event) { | |
var status = event.target.status; | |
var response = event.target.response; | |
// if the remaining valid time for the current user session is less than or equals to 0 seconds. | |
if (status === 200 && (response <= 0)) { | |
window.location.href = '/session_timeout'; | |
} | |
}; | |
request.open('GET', '/check_session_timeout', true); | |
request.responseType = 'json'; | |
request.send(); | |
setTimeout(pollForSessionTimeout, (sessionTimeoutPollFrequency * 1000)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, thanks for your work, this helped me,
just you need to know that, you have to update your code to work if user interacted with the page