Skip to content

Instantly share code, notes, and snippets.

@RitwikGA
Last active May 5, 2019 12:53
Show Gist options
  • Save RitwikGA/465446874b67b06f40416f40c0d1025b to your computer and use it in GitHub Desktop.
Save RitwikGA/465446874b67b06f40416f40c0d1025b to your computer and use it in GitHub Desktop.
Time On Visible and Hidden Page
<script>
(function(){
// Initialize time
var startTime = new Date().getTime();
var totalTime = {};
if (typeof prefix() !== 'undefined') {
var prevTime = 0;
var visibilityEvent = prefix() + 'visibilitychange';
var tabPath = 'visibleTab';
//Initialize the listeners
document.addEventListener(visibilityEvent,
function(e){
var isHidden=visibilityState(prefix())
if (typeof isHidden !== 'undefined') {
prevTime = 0 ? new Date().getTime() - startTime : new Date().getTime() - startTime - prevTime;
//Total Time for previous visibility state
if(isHidden) { totalTime.visibleTime=prevTime; tabPath+=">hiddenTab"}
else {totalTime.hiddenTime=prevTime; tabPath+=">visibleTab" }
}
//////Debugging Datalayer Event /////////
dataLayer.push({
'event' : 'visibilityChange',
'visibleTime' : totalTime.visibleTime,
'hiddenTime': totalTime.hiddenTime,
'hidden' : isHidden,
'tabPath': tabPath
});
///////////////
}, false);
window.addEventListener('beforeunload', function(e)
{
var isHidden=visibilityState(prefix())
if (typeof isHidden !== 'undefined') {
prevTime = 0 ? new Date().getTime() - startTime : new Date().getTime() - startTime - prevTime;
if(!isHidden){totalTime.visibleTime=prevTime}
else {totalTime.hiddenTime=prevTime}
}
if(tabPath.split('>').length > 3) {
var len = Math.floor(tabPath.split('>').length / 2);
var adtxt = ''
if(tabPath.split('>').length / 2 % 1 !== 0){adtxt+=' > visibleTab';}
tabPath = '(visibleTab > hiddenTab) x '+len+adtxt
}
dataLayer.push({
'event' : 'sendTimings',
'visibleTime' : totalTime.visibleTime,
'hiddenTime': totalTime.hiddenTime,
'hidden' : isHidden,
'tabPath': tabPath
});
// reset the variables after sending data to analytics
prevTime=0;
startTime = new Date().getTime();
totalTime = {};
tabPath = 'visibleTab';
}, false);
}
})()
function prefix() {
var prefixes = ['moz', 'ms', 'o', 'webkit'];
if ('hidden' in document) {
return '';
}
// Loop through each prefix to see if it is supported.
for (var i = 0; i < prefixes.length; i++) {
var testPrefix = prefixes[i] + 'Hidden';
if (testPrefix in document) {
return prefixes[i];
}
}
return;
}
function visibilityState(pref){
switch (pref) {
case '':
return document['hidden'];
case 'moz':
return document['mozHidden'];
case 'o':
return document['oHidden'];
case 'webkit':
return document['webkitHidden'];
default:
return;
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment