UNPKG

17.1 kBMarkdownView Raw
1Autotrack
2=========
3
4[![Sauce Test Status](https://saucelabs.com/browser-matrix/autotrack.svg)](https://saucelabs.com/u/autotrack)
5
6## Overview
7
8The default [JavaScript tracking snippet](https://developers.google.com/analytics/devguides/collection/analyticsjs/) for Google Analytics runs when a web page is first loaded and sends a pageview hit to Google Analytics. If you want to know about more than just pageviews (e.g. events, social interactions), you have to write code to capture that information yourself.
9
10Since most website owners care about most of the same types of user interactions, web developers end up writing the same code over and over again for every new site they build.
11
12Autotrack was created to solve this problem. It provides default tracking for the interactions most people care about, and it provides several convenience features (e.g. declarative event tracking) to make it easier than ever to understand how people are using your site.
13
14The `autotrack.js` library is small (3K gzipped), and includes the following plugins. By default all plugin are bundled together, but they can be included and configured separately as well:
15
16<table>
17 <tr>
18 <th align="left">Plugin</th>
19 <th align="left">Description</th>
20 </tr>
21 <tr>
22 <td><a href="#eventtracker"><code>eventTracker</code></a></td>
23 <td>Declarative event tracking</td>
24 </tr>
25 <tr>
26 <td><a href="#mediaquerytracker"><code>mediaQueryTracker</code></a></td>
27 <td>Media query and breakpoint tracking</td>
28 </tr>
29 <tr>
30 <td><a href="#outboundformtracker"><code>outboundFormTracker</code></a></td>
31 <td>Automatic outbound form tracking</td>
32 </tr>
33 <tr>
34 <td><a href="#outboundlinktracker"><code>outboundLinkTracker</code></a></td>
35 <td>Automatic outbound link tracking</td>
36 </tr>
37 <tr>
38 <td><a href="#sessiondurationtracker"><code>sessionDurationTracker</code></a></td>
39 <td>Enhanced session duration tracking</td>
40 </tr>
41 <tr>
42 <td><a href="#socialtracker"><code>socialTracker</code></a></td>
43 <td>Automatic and enhanced declarative social tracking</td>
44 </tr>
45 <tr>
46 <td><a href="#urlchangetracker"><code>urlChangeTracker</code></a></td>
47 <td>Automatic URL change tracking for single page applications</td>
48 </tr>
49</table>
50
51## Usage
52
53To add autotrack to your site, you have to do two things:
54
551. Load the `autotrack.js` script file on your page.
562. Update the [tracking snippet](https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference) to [require](https://developers.google.com/analytics/devguides/collection/analyticsjs/using-plugins) the `autotrack` plugin.
57
58If your site already includes the default JavaScript tracking snippet, you can replace it with the following modified snippet (note the added `require` command as well as the additional `autotrack.js` script):
59
60```html
61<script>
62window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
63ga('create', 'UA-XXXXX-Y', 'auto');
64ga('require', 'autotrack');
65ga('send', 'pageview');
66</script>
67<script async src='//www.google-analytics.com/analytics.js'></script>
68<script async src='path/to/autotrack.js'></script>
69```
70
71The [analytics.js plugin system](https://developers.google.com/analytics/devguides/collection/analyticsjs/using-plugins) is designed to support asynchronously loaded scripts, so it doesn't matter if `autotrack.js` is loaded before or after `analytics.js`. It also doesn't matter if the `autotrack.js` library is loaded individually or bundled with the rest of your JavaScript code.
72
73### Loading autotrack via npm
74
75If you use npm and a module loader like [Browserify](http://browserify.org/), [Webpack](https://webpack.github.io/), or [SystemJS](https://github.com/systemjs/systemjs), you can include autotrack in your build by requiring it as you would any other npm module:
76
77```sh
78npm install autotrack
79```
80
81```js
82// In your JavaScript code
83require('autotrack');
84```
85
86Note that the above code will include the autotrack plugins in the generated JavaScript file, but it won't register the plugin for use on an `analytics.js` tracker object. Adding the `require` command to the tracking snippet is still necessary:
87
88```js
89// In the analytics.js tracking snippet
90ga('create', 'UA-XXXXX-Y', 'auto');
91ga('require', 'autotrack');
92ga('send', 'pageview');
93```
94
95### Using individual plugins
96
97The `autotrack.js` source file includes all the plugins described below, but in some cases you might not want to use all of them.
98
99When you require the `autotrack` plugin, it runs the require command for each of the bundled plugins and passes them a copy of the configuration object it received (if any). To only use select plugins, you can require them individually instead of requiring the `autotrack` plugin.
100
101For example, to only use the `outboundLinkTracker` and `sessionDurationTracker` plugins, you can modify the snippet as follows:
102
103```js
104ga('create', 'UA-XXXXX-Y', 'auto');
105ga('require', 'outboundLinkTracker');
106ga('require', 'sessionDurationTracker');
107ga('send', 'pageview');
108```
109
110Note that the `autotrack.js` source file still includes the code for all plugins. To build a custom version of the script with only the desired plugins, see the [custom builds](#custom-builds) section below.
111
112## Plugins
113
114### `eventTracker`
115
116The `eventTracker` plugin adds declarative event tracking for click events on any element with the `data-event-category` and `data-event-action` attributes. The attributes `data-event-label` and `data-event-value` are also supported (attribute names are customizable).
117
118#### Options
119
120* [`attributePrefix`](#attributeprefix)
121
122#### Example
123
124The following element would send an event hit to Google Analytics with the category "video" and the action "play":
125
126```html
127<button data-event-category="video" data-event-action="play">Play</button>
128```
129
130### `mediaQueryTracker`
131
132The `mediaQueryTracker` plugin allows you to track what media query is active as well as how often the matching media query changes.
133
134You can tell the `mediaQueryTracker` plugin what media query data to look for via the [`mediaQueryDefinitions`](#mediaquerydefinitions) configuration option.
135
136**Important: unlike the other autotrack plugins, to use the `mediaQueryTracker` plugin you have to first make a few changes to your property settings in Google Analytics. Here's what needs to be done:**
137
1381. Log in to Google Analytics, choose the [account and property](https://support.google.com/analytics/answer/1009618) you're sending data too, and [create a custom dimension](https://support.google.com/analytics/answer/2709829) for each set of media queries you want to track (e.g. Breakpoints, Resolution/DPI, Device Orientation)
1392. Give each dimension a name (e.g. Breakpoints), select a scope of [hit](https://support.google.com/analytics/answer/2709828#example-hit), and make sure the "active" checkbox is checked.
1403. In the [`mediaQueryDefinitions`](#mediaquerydefinitions) config object, set the `name` and `dimensionIndex` values to be the same as the name and index shown in Google Analytics.
141
142#### Options
143
144* [`mediaQueryDefinitions`](#mediaquerydefinitions)
145
146#### Example
147
148The following configuration will track breakpoint, device resolution, and device orientation data:
149
150```js
151ga('require', 'autotrack', {
152 mediaQueryDefinitions: [
153 {
154 name: 'Breakpoint',
155 dimensionIndex: 1,
156 items: [
157 {name: 'sm', media: 'all'},
158 {name: 'md', media: '(min-width: 30em)'},
159 {name: 'lg', media: '(min-width: 48em)'}
160 ]
161 },
162 {
163 name: 'Resolution',
164 dimensionIndex: 2,
165 items: [
166 {name: '1x', media: 'all'},
167 {name: '1.5x', media: '(min-resolution: 144dpi)'},
168 {name: '2x', media: '(min-resolution: 192dpi)'}
169 ]
170 },
171 {
172 name: 'Orientation',
173 dimensionIndex: 3,
174 items: [
175 {name: 'landscape', media: '(orientation: landscape)'},
176 {name: 'portrait', media: '(orientation: portrait)'}
177 ]
178 }
179 ]
180});
181```
182
183See the [`mediaQueryDefinitions`](#mediaquerydefinitions) option documentation for more details.
184
185### `outboundFormTracker`
186
187The `outboundFormTracker` plugin automatically detects when forms are submitted to sites on different domains and sends an event hit. The event category is "Outbound Form", the event action is "submit", and the event label is the value of the form's `action` attribute.
188
189### `outboundLinkTracker`
190
191The `outboundLinkTracker` plugin automatically detects when links are clicked with `href` attributes pointing to sites on different domains and sends an event hit. The event category is "Outbound Link", the event action is "click", and the event label is the value of the link's `href` attribute.
192
193### `sessionDurationTracker`
194
195Session duration in Google Analytics is defined as the amount of time between the first and last hit of a session. For a session where a user visits just one page and then leaves, the session duration is zero, even if the user stayed on the page for several minutes. Even for sessions with multiple pageviews, it can still be a problem because the duration of the last pageview is usually not considered.
196
197The `sessionDurationTracker` plugin partially solves this problem by sending an event hit to Google Analytics (in browsers that support [`navigator.sendBeacon`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon)) when the document is being unloaded. The event category is "Window" and the action is "unload". For browsers that support the [`performance.timing` API](https://developer.mozilla.org/en-US/docs/Web/API/Performance), the event value is the time since the `navigationStart` event.
198
199### `socialTracker`
200
201The `socialTracker` plugin adds declarative social interaction tracking for click events on any element with the `data-social-network`, `data-social-action`, and `data-social-target` attributes, similar to the `eventTracking` plugin.
202
203It also automatically adds social tracking for the offical Twitter tweet/follow buttons and the Facebook like button. In other words, if you include offical Twitter or Facebook buttons on your page and you're using autotrack (or even just the `socialTracker` plugin), user interactions with those buttons will be automatically tracked.
204
205The following table outlines the social fields captured:
206
207<table>
208 <tr>
209 <th align="left">Widget</th>
210 <th align="left">Social Network</th>
211 <th align="left">Social Action</th>
212 <th align="left">Social Target</th>
213 </tr>
214 <tr>
215 <td>Like button</td>
216 <td><code>Facebook</code></td>
217 <td><code>like</code> or <code>unlike</code></td>
218 <td>The URL of the current page.</td>
219 </tr>
220 <tr>
221 <td>Tweet button</td>
222 <td><code>Twitter</code></td>
223 <td><code>tweet</code></td>
224 <td>The widget's <code>data-url</code> attribute or the URL of the current page.</td>
225 </tr>
226 <tr>
227 <td>Follow button</td>
228 <td><code>Twitter</code></td>
229 <td><code>follow</code></td>
230 <td>The widget's <code>data-screen-name</code> attribute.</td>
231 </tr>
232</table>
233
234### `urlChangeTracker`
235
236The `urlChangeTracker` plugin detects changes to the URL via the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) and automatically updates the tracker and sends additional pageviews. This allows [single page applications](https://en.wikipedia.org/wiki/Single-page_application) to be tracked like traditional sites without any extra configuration.
237
238Note, this plugin does not support tracking hash changes as most Google Analytics implementations do not capture the hash portion of the URL when tracking pageviews. Also, developers of single page applications should make sure their framework isn't already tracking URL changes to avoid collecting duplicate data.
239
240#### Options
241
242* [`shouldTrackUrlChange`](#shouldtrackurlchange)
243
244
245## Configuration options
246
247The following options can be passed to the `autotrack` plugin or individual sub-plugins:
248
249### `attributePrefix`
250
251**Type**: `string`
252
253**Default**: `'data-'`
254
255The attribute prefix for declarative event and social tracking. The value used after the prefix is a kebab-case version of the field name, for example: the field `eventCategory` with the prefix `'data-ga-'` would be `data-ga-event-category`.
256
257### `mediaQueryDefinitions`
258
259**Type**: `Object|Array|null`
260
261**Default**: `null`
262
263A media query definitions object or a list of media query definition objects. A media query definitions object contains the following properties:
264
265 - `name`: a unique name that will be used as the `eventCategory` value for media query change events.
266 - `dimensionIndex`: the index of the custom dimension [created in Google Analytics](https://support.google.com/analytics/answer/2709829).
267 - `items`: An array of objects with the following properties:
268 - `name`: The value that will be set on the custom dimension.
269 - `media`: The media query value to test for a match.
270
271The following array is an example of three media query object defintions:
272
273```js
274[
275 {
276 name: 'Breakpoint',
277 dimensionIndex: 1,
278 items: [
279 {name: 'sm', media: 'all'},
280 {name: 'md', media: '(min-width: 30em)'},
281 {name: 'lg', media: '(min-width: 48em)'}
282 ]
283 },
284 {
285 name: 'Resolution',
286 dimensionIndex: 2,
287 items: [
288 {name: '1x', media: 'all'},
289 {name: '1.5x', media: '(min-resolution: 144dpi)'},
290 {name: '2x', media: '(min-resolution: 192dpi)'}
291 ]
292 },
293 {
294 name: 'Orientation',
295 dimensionIndex: 3,
296 items: [
297 {name: 'landscape', media: '(orientation: landscape)'},
298 {name: 'portrait', media: '(orientation: portrait)'}
299 ]
300 }
301]
302```
303
304If multiple `media` values match at the same time, the one specified later in the `items` array will take precedence. For example, in the "Breakpoint" example above, the item `sm` is set to `all`, so it will always match unless `md` or `lg` matches.
305
306### `mediaQueryChangeTemplate`
307
308**Type**: `Function`
309
310**Default**:
311
312```js
313function(newValue, oldValue) {
314 return oldValue + ' => ' + newValue;
315}
316```
317
318A function used to format the `eventLabel` of media query change events. For example, if the matched media changes from `lg` to `md`, by default the result will be `lg => md`.
319
320### `mediaQueryChangeTimeout`
321
322**Type**: `number`
323
324**Default**: `1000`
325
326The debounce timeout, i.e., the amount of time to wait before sending the change hit. If multiple change events occur within the timeout period, only the last one is sent.
327
328### `shouldTrackUrlChange`
329
330**Type**: `Function`
331
332**Default**:
333
334```js
335function(newPath, oldPath) {
336 return true;
337}
338```
339
340A function used to determine if a URL change should be tracked. By default, all changes other than hash changes are captured.
341
342The function is invoked with the string values `newPath` and `oldPath` which represent the pathname and search portion of the URL (not the hash portion).
343
344
345## Advanced Usage
346
347### Custom builds
348
349The autotrack library is built modularly and each plugin includes its own dependencies, so you can create a custom build of the library using a script bundler such as [Browserify](http://browserify.org/).
350
351The following example shows how to create a build that only includes the `outboundLinkTracker` and `sessionDurationTracker` plugins:
352
353```sh
354browserify lib/plugins/outbound-link-tracker lib/plugins/session-duration-tracker
355```
356
357When making a custom build, be sure to update the tracking snippet to only require plugins included in your build. Requiring a plugin that's not included in the build will prevent any subsequent `analytics.js` commands from running.
358
359If you're already using a module loader like [Browserify](http://browserify.org/), [Webpack](https://webpack.github.io/), or [SystemJS](https://github.com/systemjs/systemjs) to build your JavaScript, you can skip the above step and just require the plugins you want directly in your source files:
360
361```js
362// In your JavaScript code
363require('autotrack/lib/plugins/outbound-link-tracker');
364require('autotrack/lib/plugins/session-duration-tracker');
365```
366
367Check out the [autotrack source code](https://github.com/philipwalton/autotrack/blob/master/lib/plugins/autotrack.js) to get a better idea how this works.
368
369### Using autotrack with multiple trackers
370
371All autotrack plugins support multiple trackers and work by specifying the tracker name in the `require` command. The following example creates two trackers and requires `autotrack` on both.
372
373```js
374ga('create', 'UA-XXXXX-Y', 'auto', 'tracker1');
375ga('create', 'UA-XXXXX-Z', 'auto', 'tracker2');
376ga('tracker1.require', 'autotrack');
377ga('tracker2.require', 'autotrack');
378ga('tracker1.send', 'pageview');
379ga('tracker2.send', 'pageview');
380```
381
382
383## Disclaimer
384
385The autotrack library is not an official Google Analytics product and is not covered by Google Analytics Premium support. Developers that choose to use this library are responsible for ensuring that their implementation meets the requirements of the [Google Analytics Terms of Service](https://www.google.com/analytics/terms/us.html) and the legal obligations of their respective country.
386