Skip to content
Yali Sassoon edited this page Mar 12, 2013 · 9 revisions

HOME > [SNOWPLOW TECHNICAL DOCUMENTATION](SnowPlow technical documentation) > Trackers > Javascript Tracker

Contents

## 1. Overview

The SnowPlow Javascript tracker works in much the same way as Javascript trackers for other major web analytics solutions including Google Analytics and Omniture. We have tried, as far as possible, to keep the API very close to that used by Google Analytics, so that users who have implemented Google Analytics Javascript tags have no difficulty also implementing the SnowPlow Javascript tags.

Tracking is done by inserting Javascript tags onto pages. These tags run functions defined in snowplow.js, that trigger GET requests of the SnowPlow pixel. The Javascript functions append data points to be passed into SnowPlow onto the query string for the GET requests. These then get logged by the SnowPlow collector. For a full list of data points that can be passed into SnowPlow in this way, please refer to the SnowPlow tracker protocol documentation.

The Javascript tracker supports both syncronous and asyncronous tags. We recommend the asyncronous tags in nearly all instances, as these do not slow down page load times.

Back to top

## 2. General parameters

There are two "global parameters" that should be set for the Javascript tracker:

  1. The collector endpoint
  2. The application ID

These are generally set as part of the pageview tracking tags, before the actual trackPageView method is called e.g.

<!-- SnowPlow starts plowing -->
<script type="text/javascript">
var _snaq = _snaq || [];

_snaq.push(['setCollectorCf', '{{CLOUDFRONT-DOMAIN}}']);
_snaq.push(['setAppId', '{{MY-SITE-ID}}']);
_snaq.push(['trackPageView']);

(function() {
var sp = document.createElement('script'); sp.type = 'text/javascript'; sp.async = true; sp.defer = true;
sp.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://d1fc8wv8zag5ca.cloudfront.net/0.10.0/sp.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sp, s);
})();
 </script>
<!-- SnowPlow stops plowing -->
### 2.1 Setting the endpoint

Endpoint refers to the location of your collector: you need to point your Javascript tracker to your collector endpoint, to ensure that data generated by the tracker is logged by the collector.

If you are using a Cloudfront collector you can use setCollectorCf to set the endpoint. If you are using any other collector (e.g. the Clojure collector, or SnowCannon), then you should use setCollectorUrl.

#### 2.1.1 Setting a Cloudfront endpoint using `setCollectorCf`

You can set the collector endpoint for the Cloudfront collector using:

_snaq.push(['setCollectorCf', '{{CLOUDFRONT-SUBDOMAIN}}']);

So if your domain is d3rkrsqld9gmqf, you would include:

_snaq.push(['setCollectorCf', 'd3rkrsqld9gmqf']);

in your SnowPlow tag.

Back to top

#### 2.1.2 Setting a collector endpoint (e.g. for the Clojure collector) using `setCollector URL`

If you are running a different collector (not the Cloudfront collector) then you set the collector endpoint using:

_snaq.push(['setCollectorUrl', '{{COLLECTOR-URL}}'])

E.g. if your collector endpoint is at 'my-company.c.snplow.com' then you would include:

_snaq.push(['setCollectorUrl', 'my-company.c.snplow.com'])

in your SnowPlow tags.

Back to top

### 2.2 Setting the application ID

You can set different application IDs on different parts of your site. You can then distinguish events that occur on different applications by grouping results based on application_id.

#### 2.2.1 Setting the application ID using `setAppId`

To set the application ID, use the setAppId method i.e.:

_snaq.push(['setAppId', 'my_application_id_here']);

Back to top

### 2.3 Setting the user ID

The Javascript tracker automatically sets a domain_userid based on a first party cookie.

There are many situations, however, when you will want to identify a specific user using an ID generated by one of your business systems. To do this, you use the setUserId method.

#### 2.3.1 Setting the user ID using `setUserId`

To set the user ID, use the setUserId method i.e.:

_snaq.push(['setUserId', '[email protected]']);

Typically, companies employ this method at points in the customer journey when the user identifies him / herself e.g. if he / she logs in.

Note: this will only set the user ID on further events fired while the user is on this page; if you want events on another page to record this user ID too, you must call setUserId on the other page as well.

Back to top

## 3. Tracking specific events

SnowPlow has been built to enable users to track a wide range of events that occur when consumers interact with their websites and webapps. We are constantly growing the range of functions available in order to capture that data more richly.

### 3.1 Pageviews

Page views are tracked using the trackPageView method. This is generally part of the first SnowPlow tag to fire on a particular web page. As a result, the trackPageView method is usually deployed with "global" method like setAppId and setCollectorCf in a single tag that also invokes the SnwoPlow Javascript (sp.js) e.g.

<!-- SnowPlow starts plowing -->
<script type="text/javascript">
var _snaq = _snaq || [];

_snaq.push(['setCollectorCf', '{{CLOUDFRONT-DOMAIN}}']);
_snaq.push(['setAppId', '{{MY-SITE-ID}}']);
_snaq.push(['trackPageView']);

(function() {
var sp = document.createElement('script'); sp.type = 'text/javascript'; sp.async = true; sp.defer = true;
sp.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://d1fc8wv8zag5ca.cloudfront.net/0.10.0/sp.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sp, s);
})();
 </script>
<!-- SnowPlow stops plowing -->
#### 3.1.1 `trackPageView`

Track pageview is called using the simple:

_snaq.push(['trackPageView']);

This method automatically captures the page title, URL and referrer.

Note: going forwards we plan to extend this method to also capture page category.

Back to top

### 3.2 Track engagement with a web page over time: page pings

As well as tracking page views, we can monitor whether a user continues to engage with a page over time, and record how he / she digests content on the page over time.

That is accomplished using 'page ping' events. If activity tracking is enabled, the web page is monitored to see if a user is engaging with it. (E.g. is the tab in focus, does the mouse move over the page, does the user scroll etc.) If any of these things occur in a set period of time, a page ping event fires, and records the maximum scroll left / right and up / down in the last ping period. If there is no activity in the page (e.g. because the user is on a different tab in his / her browser), no page ping fires.

#### 3.2.1 `enableActivityTracking`

Page pings are enabled by:

_snaq.push(['enableActivityTracking', minimumVisitLength, heartBeat]);

where minimumVisitLength is the time period from page load before the first page ping occurs, in seconds. Heartbeat is the number of seconds between each page ping, once they have started. So, if you executed:

_snaq.push(['enableActivityTracking', 30, 10]);

The first ping would occur after 30 seconds, and subsequent pings every 10 seconds as long as the user continued to browse the page actively.

Note: in general this is executed as part of the main SnowPlow tracking tag. As a result, you can elect to enable this on specific pages.

Back to top

### 3.3 Ecommerce tracking

Modelled on Google Analytics ecommerce tracking capability, SnowPlow uses three methods that have to be used together track online transactions:

  1. Create a transaction object. Use addTrans() method to initialize a transaction object. This will be the object that is loaded with all the data relevant to the specific transaction that is being tracked including all the items in the order, the prices of the items, the price of shipping and the order_id.
  2. Add items to the transaction. Use the addItem() method to add data about each individual item to the transaction object.
  3. Submit the transaction to SnowPlow using the trackTrans() method, once all the relevant data has been loaded into the object.
#### 3.3.1 `addTrans`

The addTrans method creates a transaction object. It takes seven possible parameters, two of which are required:

Parameter Required? Example value
order ID Yes '1234'
affiliation or store name No 'Womens Apparel'
total spend Yes '19.99'
shipping cost No '2.99'
city No 'San Jose'
state or province No 'California'
country No 'USA'

For example:

_snaq.push(['addTrans',
    '1234',           // order ID - required
    'Acme Clothing',  // affiliation or store name
    '11.99',          // total - required
    '1.29',           // tax
    '5',              // shipping
    'San Jose',       // city
    'California',     // state or province
    'USA'             // country
  ]);

Back to top

#### 3.3.2 `addItem`

The addItem method is used to capture the details of each product item included in the transaction. It should therefore be called once for each item.

There are six potential parameters that can be passed with each call, four of which are required:

Parameter Required? Example value
order ID Yes (in order to associate item with transaction) '1234'
SKU / product code Yes 'pbz0001234'
product name No, but advisable (to make interpreting SKU easier) 'Black Tarot'
category or variation No 'Large'
unit price Yes '9.99'
quantity Yes '1'

For example:

_snaq.push(['addItem',
    '1234',           // order ID - required
    'DD44',           // SKU/code - required
    'T-Shirt',        // product name
    'Green Medium',   // category or variation
    '11.99',          // unit price - required
    '1'               // quantity - required
  ]);
#### 3.3.3 `trackTrans`

Once the transaction object has been created (using addTrans) and the relevant item data added to it using the addItem method, we are ready to send the data to the collector. This is initiated using the trackTrans method:

_snaq.push(['trackTrans']);
#### 3.3.4 Putting the three methods together: a complete example
<html>
<head>
<title>Receipt for your clothing purchase from Acme Clothing</title>
<script type="text/javascript">
  var _snaq = _snaq || [];

  _snaq.push(['setCollectorCf', 'd3rkrsqld9gmqf']);
  _snaq.push(['trackPageView']);
  _snaq.push(['enableLinkTracking']);

  (function() {
  var sp = document.createElement('script'); sp.type = 'text/javascript'; sp.async = true; sp.defer = true;
  sp.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://d1fc8wv8zag5ca.cloudfront.net/0.9.0/sp.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sp, s);
  })();


  _snaq.push(['addTrans',
    '1234',           // order ID - required
    'Acme Clothing',  // affiliation or store name
    '11.99',          // total - required
    '1.29',           // tax
    '5',              // shipping
    'San Jose',       // city
    'California',     // state or province
    'USA'             // country
  ]);

   // add item might be called for every item in the shopping cart
   // where your ecommerce engine loops through each item in the cart and
   // prints out _addItem for each
  _snaq.push(['addItem',
    '1234',           // order ID - required
    'DD44',           // SKU/code - required
    'T-Shirt',        // product name
    'Green Medium',   // category or variation
    '11.99',          // unit price - required
    '1'               // quantity - required
  ]);

  // trackTrans sends the transaction to SnowPlow tracking servers.
  // Must be called last to commit the transaction.
  _snaq.push(['trackTrans']); //submits transaction to the collector

</script>
</head>
<body>

  Thank you for your order.  You will receive an email containing all your order details.

</body>
</html>

Back to top

### 3.4 Social tracking

Social tracking has not been implemented yet. However, the intention is to use a similar tracking function to that employed by Google Analytics.

Social tracking will be used to track the way users interact with Facebook, Twitter and Google + widgets, e.g. to capture "like this" or "tweet this" events.

#### 3.4.1 `trackSocial`

The trackSocial method takes four parameters:

Parameter Description Required? Example value
network Social network Yes 'facebook', 'twitter'
socialAction Social action performed Yes 'like', 'retweet'
opt_target Object social action is performed on e.g. page ID, product ID No '19.99'
opt_pagePath Page path of URL on which social action was carried out No '2.99'

The method is executed in as:

_snaq.push('trackSocial', network, socialAction, opt_target, opt_pagePath)

For example:

_snaq.push('trackSocial', 'facebook', 'like', 'pbz00123', '/products/tarot/123-original-rider-waite')

Or if the optional parameters were left off:

_snaq.push('trackSocial', 'facebook', 'like', '', '')

Back to top

### 3.5 Campaign tracking

Campaign tracking is used to identify the source of traffic coming to a website.

At the highest level, we can distinguish paid traffic (that derives from ad spend) with non paid traffic: visitors who come to the website by entering the URL directly, clicking on a link from a referrer site or clicking on an organic link returned in a search results, for example.

In order to identify paid traffic, SnowPlow users need to set five query parameters on the links used in ads. SnowPlow checks for the presence of these query parameters on the web pages that users load: if it finds them, it knows that that user came from a paid source, and stores the values of those parameters so that it is possible to identify the paid source of traffic exactly.

If the query parameters are not present, SnowPlow reasons that the user is from a non paid source of traffic. It then checks the page referrer (the url of the web page the user was on before visiting our website), and uses that to deduce the source of traffic:

  1. If the URL is identified as a search engine, the traffic medium is set to "organic" and SnowPlow tries to derive the search engine name from the referrer URL domain and the keywords from the query string.
  2. If the URL is a non-search 3rd party website, the medium is set to "referrer". SnowPlow derives the source from the referrer URL domain.
#### 3.5.1 Identifying paid sources

Your different ad campaigns (PPC campaigns, display ads, email marketing messages, Facebook campaigns etc.) will include one or more links to your website e.g.:

<a href="http://mysite.com/myproduct.html">Visit website</a>

We want to be able to identify people who've clicked on ads e.g. in a marketing email as having come to the site having clicked on a link in that particular marketing email. To do that, we modify the link in the marketing email with query parameters, like so:

<a href="http://mysite.com/myproduct.html?utm_source=newsletter-october&utm_medium=email&utm_campaign=cn0201">Visit website</a>

For the prospective customer clicking on the link, adding the query parameters does not change the user experience. (The user is still directed to the webpage at http://mysite.com/myproduct.html.) But SnowPlow then has access to the fields given in the query string, and uses them to identify this user as originating from the October Newsletter, an email marketing campaign with campaign id = cn0201.

#### 3.5.2 Anatomy of the query parameters

SnowPlow uses the same query parameters used by Google Analytics. Because of this, SnowPlow users who are also using GA do not need to do any additional work to make their campaigns trackable in SnowPlow as well as GA. Those parameters are:

Parameter Name Description
utm_source Campaign source Identify the advertiser driving traffic to your site e.g. Google, Facebook, autumn-newsletter etc.
utm_medium Campaign medium The advertising / marketing medium e.g. cpc, banner, email newsletter, in-app ad, cpa
utm_campaign Campaign id A unique campaign id. This can be a descriptive name or a number / string that is then looked up against a campaign table as part of the analysis
utm_term Campaign term(s) Used for search marketing in particular, this field is used to identify the search terms that triggered the ad being displayed in the search results.
utm_content Campaign content Used either to differentiate similar content or two links in the same ad. (So that it is possible to identify which is generating more traffic.)

The parameters are descibed in the [Google Analytics help page] [gahelppage]. Google also provides a [urlbuilder] [gaurlbuilder] which can be used to construct the URL incl. query parameters to use in your campaigns.

Back to top

### 3.6 Ad impression tracking

SnowPlow tracking code can be included in ad tags in order to track impressions. This is used by e.g. ad networks to identify which sites and web pages users visit across a network, so that they can be segmented, for example.

Impression tracking is accomplished using the trackImpression method.

#### 3.6.1 `trackImpression`

The method takes four parameters:

Name Required? Description
BannerID Yes Adserver identifier for the ad banner (creative) being displayed
CampaignID No Adserver identifier for the ad campaign which the banner belongs to
AdvertiserID No Adserver identifier for the advertiser which the campaign belongs to
UserID No Adserver identifier for the web user. Not to be confused with SnowPlow's own user identifier

You will want to set these arguments programmatically, across all of your ad zones/slots - for guidelines on how to achieve this with the [OpenX adserver] openx, please see the following sub-sections.

3.6.2 Example: implementing impression tracking with SnowPlow and OpenX

Most ad servers enable you to append custom code to your ad tags. Here's what the zone append functionality looks like in the OpenX adserver (OnRamp edition):

zoneappend zoneappend

You will need to populate the ad zone append field with SnowPlow tags for every ad zone/unit which you use to serve ads across your site or network. Read on for the SnowPlow HTML code to use for OpenX.

OpenX: SnowPlow impression tracking using magic macros

Because OpenX has a feature called [magic macros] magicmacros, it is relatively straightforward to pass the banner, campaign and user ID arguments into the call to trackImpression() (advertiser ID is not available through magic macros).

The full HTML code to append, using asynchronous SnowPlow invocation, looks like this:

<!-- SnowPlow starts plowing -->
<script type="text/javascript">
var _snaq = _snaq || [];

_snaq.push(['setCollectorCf', 'patldfvsg0d8w']); // Update to your CloudFront distribution subdomain
_snaq.push(['trackImpression', '{bannerid}', '{campaignid}', '', '{OAID}']); // OpenX magic macros. Leave this line as-is

(function() {
var sp = document.createElement('script'); sp.type = 'text/javascript'; sp.async = true; sp.defer = true;
sp.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://d107t3sdgumbla.cloudfront.net/sp.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sp, s);
})();
 </script>
<!-- SnowPlow stops plowing -->

Once you have appended this code to all of your active ad zones, SnowPlow should be collecting all of your ad impression data.

Back to top

Back to top

### 3.7 Tracking custom structured events

There are likely to be a large number of AJAX events that can occur on your site, for which a specific tracking method is part of SnowPlow. Examples include:

  • Playing a video
  • Adding an item to basket
  • Submitting a lead form

Our philosophy in creating SnowPlow is that users should capture "every" consumer interaction and work out later how to use this data. This is different from traditional web analytics and business intelligence, that argues that you should first work out what you need, and only then start capturing the data.

As part of a SnowPlow implementation, therefore, we recommend that you identify every type of AJAX interaction that a user might have with your site: each one of these is an event that will not be captured as part of the standard page view tracking. All of them are candidates to track using trackStructEvent, if none of the other event-specific methods outlined above are appropriate.

3.7.1 trackStructEvent

There are 5 parameters can be associated with each structured event. Of them, only the first two are required:

Name Required? Description
Category Yes The name you supply for the group of objects you want to track e.g. 'media', 'ecomm'
Action Yes A string which defines the type of user interaction for the web object e.g. 'play-video', 'add-to-basket'
Label No An optional string which identifies the specific object being actioned e.g. ID of the video being played, or the SKU or the product added-to-basket
Property No An optional string describing the object or the action performed on it. This might be the quantity of an item added to basket
Value No An optional float to quantify or further describe the user action. This might be the price of an item added-to-basket, or the starting time of the video where play was just pressed

The async specification for the trackStructEvent method is:

_snaq.push(['trackStructEvent', 'category','action','object','property','value'])

An example of tracking a user listening to a music mix:

_snaq.push(['trackStructEvent', 'Mixes', 'Play', 'MrC/fabric-0503-mix', '', '0.0'])

Note that in the above example no value is set for the event property.

Back to top

### 3.8 Tracking custom unstructured events

This feature is on the roadmap: it has not been developed yet.

#### 3.8.1 `trackUnstructEvent`

This feature is on the roadmap: it has not been developed yet.

Back to top

### 3.9 Link click tracking

This feature is on the roadmap: it has not been developed yet.

#### 3.9.1 `enableLinkTracking`

This feature is on the roadmap: it has not been developed yet.

Back to top

Clone this wiki locally