Skip to content

Instantly share code, notes, and snippets.

@vicmaster
Forked from RitwikGA/Visible&HiddenTimeOnPage
Created January 22, 2018 18:46
Show Gist options
  • Save vicmaster/2be99ad92705c3aab61c283a62502dc1 to your computer and use it in GitHub Desktop.
Save vicmaster/2be99ad92705c3aab61c283a62502dc1 to your computer and use it in GitHub Desktop.
Time On Visible and Hidden Page
var prefix=function() {
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;
}
var visibilityState = function(pref){
switch (pref) {
case '':
return document['hidden'];
case 'moz':
return document['mozHidden'];
case 'o':
return document['oHidden'];
case 'webkit':
return document['webkitHidden'];
default:
return;
}
}
// Initialize time
var startTime = new Date().getTime();
var totalTime = {};
if (typeof prefix() !== 'undefined') {
var prevTime = 0;
var visibilityEvent = prefix() + 'visibilitychange';
function visibilityChanged()
{
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}
else {totalTime.hiddenTime=prevTime}
}
//////Debugging Datalayer Event /////////
dataLayer.push({
'event' : 'visibilityChange',
'visibletime' : totalTime.visibleTime,
'hiddentime': totalTime.hiddenTime,
'hidden' : isHidden
});
///////////////
};
function sendTimings()
{
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}
}
dataLayer.push({
'event' : 'sendTimings',
'visibleTime' : totalTime.visibleTime,
'hiddenTime': totalTime.hiddenTime,
'hidden' : isHidden
});
// reset the variables after sending data to analytics
prevTime=0;
startTime = new Date().getTime();
totalTime = {}
}
//Initialize the listeners
document.addEventListener(visibilityEvent, visibilityChanged, false);
window.addEventListener('beforeunload', sendTimings, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment