A utility which makes common tracking tasks with Google Analytics more reliable and less error-prone:
- Ensures tracking features, such as
hitCallback
, work regardless if GA is loaded or is blocked by an ad blocker. - Can automatically track events on HTML elements with the data attribute
data-track
and attempt to register the hit before the page is redirected. - Can remove UTM parameters from from the URL after their values have registered.
GAHelper
will include Google Analytics base code if it is not present on the page.- Includes a configurable timeout for the tracking hit to register before gracefully failing.
GAHelper
’s methods can be mixed and matched with their native GA counterparts.- Handles setting
page
andlocation
variables to ensure proper page tracking with single page applications.
<head>
<script src="GAHelper.min.js"></script>
<script>
GAHelper.create('UA-XXXXX-Y').pageview({
clearUTM: true
});
</script>
...
</head>
<a href="/more" data-track="footer,more,ft_more">Learn more</a>
element.addEventListener('click', function() {
GAHelper.event({
eventCategory: 'header',
eventAction: 'nav_home',
eventLabel: 'hd_nav_logo',
hitCallback: function(success) {
if ( ! success) {
console.log('GA event failed to register, or GA was disabled by an ad blocker.');
}
}
});
});
Note: Methods can be mixed and matched with their native GA counterparts. You only need to use the methods you find helpful.
-
GAHelper.forceTry
Boolean
- Specifies ifGAHelper
should attempt to register event hits regardless if GA has loadedtrue
, or not to attemptfalse
; defaults tofalse
.- This flag is designed to speed up the calling of
hitCallback
in the event that GA has been blocked by an ad blocker. - Page views are always attempted regardless of GA load status as page views are often requested immediately after the GA base code and before the asynchronous script has loaded.
- This flag is designed to speed up the calling of
-
GAHelper.timeout
Number
- The time, in milliseconds, for the tracking hit to register before assuming it failed; defaults to2000
. -
GAHelper.trackerName
String
- Name of the tracker object. By defining the tracker name here, or by definingfieldsObject.name
toGAHelper.create
, allGAHelper.pageview
,GAHelper.event
, andGAHelper.send
calls will automatically be prefixed/namespaced with the tracker name.
Creates a new tracker instance and will include the Google Analytics base code if it is not present on the page. This method returns the instance of GAHelper
to allow for method chaining.
GAHelper.create
requires either a trackingId
or fieldsObject
:
- trackingId
String
- The tracking ID / web property ID. - fieldsObject
Object
- Alternatively, a fields object may also be used to specify multiple fields together.
Examples:
GAHelper.create('UA-XXXXX-Y');
GAHelper.create({
trackingId: 'UA-XXXXX-Y',
cookieDomain: 'auto',
name: 'myTracker'
});
Sends a pageview hit to Google Analytics. This method returns the instance of GAHelper
to allow for method chaining.
- [fieldsObject]
Object
- An optional field object:- [fieldsObject.title]
String
- The optional title of the page. - [fieldsObject.location]
String
- The optional URL of the page being tracked. - [fieldsObject.page]
String
- The optional path portion of a URL. This value should start with a slash (/) character. - [fieldsObject.clearUTM]
Boolean
- Specifies if the UTM parameters should be removed from the URL after the page view has been recordedtrue
, or notfalse
; defaults tofalse
. SeeGAHelper.clearUTM
for additional details. - [fieldsObject.hitCallback]
Function
- The optional function that will be called after processing a hit. The callback function is passed aBoolean
with the value oftrue
if the hit was recorded, orfalse
if the request timed out or was blocked.
- [fieldsObject.title]
Example:
GAHelper.pageview();
GAHelper.pageview({
page: '/buy',
clearUTM: true,
hitCallback: function(success) {
if ( ! success) {
console.log('Pageview failed to register, or GA was disabled by an ad blocker.');
}
}
});
Sends an event hit to Google Analytics. This method returns the instance of GAHelper
to allow for method chaining.
- fieldsObject
Object
- A field object:- fieldsObject.eventCategory
String
- Specifies the event category. - fieldsObject.eventAction
String
- Specifies the event action. - [fieldsObject.eventLabel]
String
- Specifies the optional event label. - [fieldsObject.eventValue]
Number
- Specifies the optional event value - [fieldsObject.hitCallback]
Function
- The optional function that will be called after processing a hit. The callback function is passed aBoolean
with the value oftrue
if the hit was recorded, orfalse
if the request timed out or was blocked.
- fieldsObject.eventCategory
Example:
GAHelper.event({
eventCategory: 'header',
eventAction: 'nav_home',
hitCallback: function(success) {
if ( ! success) {
console.log('Event failed to register, or GA was disabled by an ad blocker.');
}
}
});
Sends a hit to Google Analytics. Typically you will use GAHelper.pageview
or GAHelper.event
, but GAHelper.send
is exposed if you wish to track "social" or "timing" hit types. This method returns the instance of GAHelper
to allow for method chaining.
- fieldsObject
Object
- A field object that defines the hit type and fields.
Example:
GAHelper.send({
hitType: 'social',
socialNetwork: 'Facebook',
socialAction: 'like',
socialTarget: 'http://example.com',
hitCallback: function(success) {
if ( ! success) {
console.log('Hit failed to register, or GA was disabled by an ad blocker.');
}
}
});
Sets up attribute tracking by adding events to the document
to listen for interactions on HTML elements with the data attribute data-track
. Only needs to be called once per page load.
This method returns the instance of GAHelper
to allow for method chaining.
Removes Google Analytics UTM parameters from the URL using history.replaceState
.
GAHelper
can also be configured to automatically remove UTM codes after the initial GAHelper.pageview
has been recorded.
While removing UTM codes creates a visually cleaner URL, visitors who copy and share the browser URL will not copy the UTM codes going forward. You will lose any measurement of share “spray” and the attribution to the original source. This may be desired, but should be considered before implementing.
This method returns the instance of GAHelper
to allow for method chaining.
Determines if the Google Analytics base code and ga
variable are present true
, or unavailable false
.
Determines if the Google Analytics asynchronous script has loaded true
, or is unavailable or still loading false
.
GAHelper
will detect HTML elements with the data attribute data-track
and automatically send the defined value to GAHelper.event
when the element is clicked or the form is submitted. GAHelper
will attempt to register the hit before the page is redirected.
- track
String
- A comma-separatedString
that defines theevent
hit. Whitespace before and after commas is trimmed and ignored.- eventCategory
String
- Specifies the event category. - eventAction
String
- Specifies the event action. - [eventLabel]
String
- Specifies the optional event label. - [eventValue]
Number
- Specifies the optional event value
- eventCategory
Note: Before data attributes will automatically track, you need to initialize the listeners by calling GAHelper.initAttributeTracking().
Example:
<ul>
<li><a href="/buy" data-track="footer, buy, ft_buy">Buy now</a></li>
<li><a href="https://www.google.com/maps" target="_blank" data-track="footer,exit_link,ft_map">Find our store</a></li>
<li><a href="mailto:[email protected]" data-track="footer,email,ft_email">Email us</a></li>
</ul>
Acts identical to data-track
except that GAHelper
does not wait for the hit to register before allowing the default element behavior. Helpful when developing single page applications.
Note: Before data attributes will automatically track, you need to initialize the listeners by calling GAHelper.initAttributeTracking().
Example:
<a href="#" data-track-async="footer,buy,ft_buy">Buy now</a></li>
GAHelper
can be used freely for any open source or commercial works and is released under a MIT license.
This project was highly influenced by Jeff Burger – the best analyst we know.
JavaScript authored by Aaron Clinger & Lucas J. Shuman.