How to Track Page Visibility in Google Analytics

how-to-track-page-1Most users frequently have several tabs open on their browsers. They may switch back and and forth from one to another or they may even leave tabs open for days at a time. This makes measuring time on page extra difficult. One solution is to track page visibility.

Using Variables

By defining variables, creating triggers, and setting up a Custom HTML tag, you can pass all the relevant information to Google Analytics through event tags.

Create Variables

First, you need to create two user-defined variables. Head to “Select Container” under “Accounts” and choose “Variables.” Under “User-Defined Variable,” click “New.”

The first variable needs the name “Data Layer - Page Visible.” Set the type as “Data Layer Variable” and give it the name “page-visible.” The data layer version is 2.

The second variable is called “Data Layer - Time - Change.” Use the same type and data layer version, but make the data layer variable name “time-change.”how-to-track-page-2Configure Triggers

Next, you need to configure triggers to fire when the DOM is ready and to fire your Google Analytics events.

Under “Select Container,” choose “Triggers” and click “New.” Name the trigger “DOM Ready” and choose the event “Page View.” Configure the trigger by giving it the trigger type “DOM Ready” and fire on all page views.

Create another trigger with the name “Page - Visibility - Visible - Event,” setting it as a custom event with the event name “gtm.page.visibility.event.” Set the conditions “data layer - page visible equals false” and “data layer - time - change greater than 0.”

The final trigger should be called “Page - Visibility - Hidden - Event.” It is a custom event with the same event name as above. Give it the configurations “data layer - page visible equals true” and “data layer - time - change greater than 0.”how-to-track-page-3Custom HTML Tag

Create a new tag with the name “Capture - Page - Visibility Change.” This needs to be a Custom HTML Tag that fires on DOM Ready. In the HTML field, add the following code:

<script>
try {
var hidden;

var visibilityChange;
if (typeof document.hidden !== “undefined”) { // Opera 12.10 and Firefox 18 and later support
hidden = “hidden”;
visibilityChange = “visibilitychange”;
} else if (typeof document.mozHidden !== “undefined” {
hidden = “mozHidden”;
visibilityChange = “mozvisibilitychange”;
} else if (typeof document.msHidden !== “undefined”) {
hidden = “msHidden”;
visibilityChange = “msvisibilitychange”;
} else if (typeof document.webkitHidden !== “undefined”) {
hidden = “webkitHidden”;
visibilityChange = “webkitvisibilitychange”;
} else if (typeof document.oHidden !== “undefined”) {
hidden = “oHidden”;
}

var date = new Date();
var currentTime = date.getTime();
var startTime = currentTime;

var handleVisibilityChange = function(customState) {
try {
var date = new Date();
var currentTime = date.getTime();
var changeTime = date.getTime() - startTime;
changeTime = Math.round(changeTime / 1000);

if(customState !== true && customState !== false) {
customState = document[hidden] ? false : true;
}

dataLayer.push({
‘event’ : ‘gtm.page.visibility.event’,
‘page-visible’ : customState,
‘time-change’ : changeTime
});

startTime = currentTime;
} catch(e) {
}
}

if (typeof document.addEventListener === “undefined” || typeof document[hidden] === “undefined”) {
// Not Supported
} else {
// Handle page visibility change
if (typeof window.addEventListener != “undefined”) {
window.addEventListener(‘beforeunload’, function(event) {
handleVisibilityChange(false);
}, false);
}

document.addEventListener(visibilityChange, function(event) {
handleVisibilityChange();
}, false);
}

} catch (e) {
}
</script>

Event Tags

Lastly, you need to configure Universal Analytics event tags.

Create one tag called “Global Content - Visible - Event” selecting the product “Google Analytics” and tag type “Universal Analytics.” Input your Google Analytics property tracking ID, set “Event” for track type, “Content” for category, “Page Visibility” for action, “Visible” for label, and “{{Data Layer - Time - Change}}” for value. Set this tag to fire on “Page - Visibility - Visible - Event.” Under “More Settings,” head to “Fields to Set” and set “useBeacon” to true.how-to-track-page-4The second tag should be “Global - Content - Hidden - Event.” This tag needs the same settings as above, except the label should be “Hidden” and the tag needs to fire on “Page - Visibility - Hidden - Event.”

Using Page Visibility API

There is another way to track page visibility with GTM. It involves using Page Visibility API for web browsers. This uses some properties of the document object to determine whether your page is visible to a user. To set it up, you need to create a visibility listener and block page views when pages are not visible.

The visibility listener sends a browser event whenever the visibility state changes for the page. It requires two Custom JavaScript Macros.

The first is a {{visibility prefix}}. This returns the browser prefix for setting up the listener and tests visibility state. It uses the following code:

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;
}

The next macro is {{visibility hidden}}, to retrieve the state of the document. When true, the document is hidden. When false, the document is visible. Use this code:

function() {
switch ({{visibility prefix}}) {
case ‘:
return
return document[‘hidden’];
case ‘moz’:
return document[‘mozHidden’];
case ‘o’:
return document[‘oHidden’];
case ‘webkit’:
return document[‘webkitHidden’];
default:
return;
}
}

You also need to create a Custom HTML tag using this code:

<script>
if (typeof {{visibility prefix}} !== ‘undefined’) {

var visibilityEvent = {{visibility prefix}} + ‘visibilitychange’,
hiddenState = {{visibility hidden}},
visibilityChanged = function() {
if (typeof hiddenState !== ‘undefined’) {
dataLayer.push({
‘event’ : ‘visibilityChange’
});
}
};

// Attach visibility listener to document
document.addEventListener(visibilityEvent, visibilityChanged, false);
}
</script>

Set the tag to fire on {{event}} equals gtm.js. If visibility changes, it will push a dataLayer event.

Finally, you need to apply the same to all events to prevent sessions occurring with events but no page views. Create a Custom JavaScript Macro {{visibility callback}} with this code:

function() {
return function() {
if (typeof {{visibility prefix}} !== ‘undefined’) {
var visibilityEvent = {{visibility prefix}} + ‘visibilitychange’;
document.removeEventListener(visibilityEvent, visibilityChanged);
}
}
}

Next, head to your page view tag. You need to create a rule with the conditions {{event}} equals visibilityChange and {{visibility hidden}} equals false. Also add the blocking rule {{visibility hidden}} equals true. Under “Fields to Set” add a new field called “hitCallback” with the value {{visibility callback}}.

If you want to receive accurate information about when users are viewing a page from your website, tracking visibility is essential. If you use the first set of instructions, you can also take further steps and set up custom metrics.

If you like my articles,