This guide describes how to use page tracking with analytics.js
Overview
Page tracking allows you to measure the number of views you had of a particular page on your web site. For a web app, you might decide to track a page when a large portion of the screen changes, for example when the user goes from the home screen to the settings screen.
There are 3 fields that can be sent with each tracking beacon to identify a page:
| Value | Type | Required | Description |
|---|---|---|---|
| Location | String |
No | URL of the page being tracked. By default, analytics.js sets this to the full document URL, excluding the fragment identifier. |
| Page | String |
No | The page path and query string of the page (e.g. /homepage?id=10).
This value must start with a / character. |
| Title | String |
No | The title of the page (e.g. homepage) |
Implementation
The default JavaScript snippet for analytics.js contains a page tracking call, so on most sites, page tracking is already happening through the default snippet.
To send a pageview, you pass the ga function
a send command with the pageview hit type:
ga('send', 'pageview');
When this command is executed, the analytics.js library
sets the title value using the document.title
browser property. The library also sets the location value
using the following browser properties and logic:
var location = window.location.protocol +
'//' + window.location.hostname +
window.location.pathname +
window.location.search;
Once calculated, the location value is sent to Google Analytics
servers where the rest of the page values are set. The hostname
value is set using the hostname portion of the location.
The page value is set using both the pathname
and search portion of the URL.
Overriding Default Values
If you need to override the default location information, you should
update the title and page
values directly.
To override the default page value, you
can pass the ga command an additional parameter:
ga('send', 'pageview', '/my-overridden-page?id=1');
Alternatively, to override these values, the send command
accepts an optional field object as the last parameter. The field object
is a standard JavaScript object, but defines specific field names and
values accepted by analytics.js.
ga('send', 'pageview', {
'page': '/my-overridden-page?id=1',
'title': 'my overridden page'
});
Finally, the hitType parameter has its own field name,
so you can send a pageview using only the send command
and a field object:
ga('send', {
'hitType': 'pageview',
'page': '/my-overridden-page?id=1',
'title': 'my overridden page'
});
Read the Field Reference document for a complete list of all the fields that can be used in the configuration object.