My current challenge involves tracking the time a user spends with a specific window in focus. I aim to record this duration accurately and pause the timer when the user switches to another window, then resume it upon returning. Ultimately, I want to measure how long it takes for a user to read the content displayed on the page.
This is part of a review process where trusted members need to log their reading time. By maintaining a running total, discrepancies between user-reported times and actual window activity can be identified for further investigation.
My approach entails utilizing JavaScript to create a timer that runs when the window is in focus, pauses during blur or closure events, and sends data back to the server via Ajax calls. Any subsequent return visits by the user would add to the existing time record.
I've encountered issues with onUnload not working as expected, especially when the browser is closed. As a workaround, I'm considering launching a new window upon document closure to trigger the logging process before self-closing.
If anyone has a more efficient solution for this scenario, particularly addressing concerns about design flaws, I'm eager to hear suggestions. (Please note that compatibility with IE7 is necessary due to our intranet environment.)
Below is a snippet of code I've been testing, but encountering some challenges:
<script type="text/javascript">
var closeMe = 0;
var logMe = 0;
function onBlur() {
closeMe = setInterval('window.close()',120000);
};
function onFocus(){
clearInterval(closeMe);
logMe = setInterval('logTime()',60000);
};
function logTime() {
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "ajax-on-time-interval.php", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
}
if (/*@cc_on!@*/false) {
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
</script>