JavaScript tracking API

The following API allows the user to:

  • track page views
  • track visits on multiple domains and subdomains
  • track e-commerce events (successful orders, cart changes, product and category views)
  • track content impressions
  • manage custom variables to use them later
  • track clicked links to external domains and download files

Installing Tracking code

There are two ways of installing a tracking code:

Installing tracking code via Tag Manager

This is the easiest and recommended way of tracking code installation. When Tag Manager is added to the site - it automatically publishes tracking code (using “Piwik PRO Analytics template”).

If you do not have Tag Manager on your website yet, follow this procedure to install it:

  1. Sign in to your PPAS with your admin or Super User account.
  2. Click on the menu button on the top left.
  3. Click on the “Websites” position.
  4. Choose the website for which you want to implement a tracking code.
  5. Select the “Installation” tab.
  6. The Tag Manager code snippet for your website is displayed under the “Website code for asynchronous tags” or “Website code for synchronous tags”.

Command queue

Loading snippet creates the following API function:

_paq.push(command)

JavaScript API interface.

Arguments:
  • command (Array<string>) – Array containing command name followed by its arguments. The number of arguments and their function depend on command.
Return type:

undefined

Commands

Trigger tracking on demand

Trigger custom event

Trigger (custom) events bound to user actions:

_paq.push(["trackEvent", category, action, name, value, dimensions]);
category

Required string Event category.

action

Required string Event action.

name

Optional string Event name.

value

Optional number Event value.

dimensions

Optional object Custom dimensions which should be tracked using this action. It can set multiple dimensions at once. Dimensions are defined as object properties using the dimension{ID} notation.

Example:

{
   dimension1: "example value",
   dimension2: "example value"
}

Example of usage (tracking when the user clicks on the cancel button with exit intent):

_paq.push(["trackEvent", "Exit intent", "Click on button", "Cancel"]);

Track goal conversion

Allows the manual tracking of goal conversion. Used in Goals - Days to Conversion report. Command:

_paq.push(["trackGoal", goal_name, goal_value, dimensions]);
goal_name

Required string Goal Name

goal_value

Optional number Tracked conversion value.

dimensions

Optional object Custom dimensions which should be tracked using this action. Dimensions are defined as object properties using the dimension{ID} notation.

Example:

{
   dimension1: "example value",
   dimension2: "example value"
}

Example of usage:

_paq.push(["trackGoal" 1, 15]);

Ecommerce tracking

Adding Ecommerce item

To add an e-commerce item (for example to track changes in the user’s cart using trackEcommerceCartUpdate), use the addEcommerceItem function:

_paq.push(["addEcommerceItem", productSKU, productName, productCategory, productPrice, productQuantity]);

Note

This function does not send any data to the Analytics. It only prepares E-commerce cart/order state to be sent with trackEcommerceOrder or trackEcommerceCartUpdate.

productSKU

Required string Product stock-keeping unit.

productName

Optional string Product name.

productCategory

Optional Array<string>|string Product category, can be written as Array with up to 5 elements.

productPrice

Optional number with product price.

productQuantity

Optional number with product quantity.

Warning

Product SKU, names and categories should be URL encoded.

Warning

The state of the cart is not maintained across the visit. You must add all products after each page view.

Example of usage:

_paq.push(["addEcommerceItem", "craft-311", "Unicorn Iron on Patch", "Crafts & Sewing", 499, 3]);

Remove Ecommerce item

To remove an e-commerce item (for example to track changes in the user’s cart using trackEcommerceCartUpdate), use the removeEcommerceItem function:

_paq.push(["removeEcommerceItem", productSKU]);

Note

This function does not send any data to the Analytics. It only prepares E-commerce cart/order state to be sent with trackEcommerceOrder or trackEcommerceCartUpdate.

productSKU

Required string Product stock-keeping unit.

Warning

Product SKU, names and categories should be URL encoded.

Warning

The state of the cart is not maintained across the visit. You must add all products after each page view.

Example of usage:

_paq.push(["removeEcommerceItem", "craft-311"]);

Clear Ecommerce items

To clear all e-commerce items (for example to track changes in the user’s cart using trackEcommerceCartUpdate), use the clearEcommerceCart function:

_paq.push(["clearEcommerceCart"]);

Note

This function does not send any data to the Analytics. It only prepares E-commerce cart/order state to be sent with trackEcommerceOrder or trackEcommerceCartUpdate.

Warning

The state of the cart is not maintained across the visit. You must add all products after each page view.

Example of usage:

_paq.push(["clearEcommerceCart"]);

Tracking Ecommerce order

To successfully track the e-commerce order(s) (on the checkout page, for example) use the trackEcommerceOrder function:

_paq.push(["trackEcommerceOrder", orderId, orderGrandTotal, orderSubTotal, orderTax, orderShipping, orderDiscount]);
orderId

Required string Unique order ID.

orderGrandTotal

Required number Order Revenue grand total - tax, shipping and discount included.

orderSubTotal

Optional number Order subtotal - without shipping.

orderTax

Optional number Order tax amount.

orderShipping

Optional number Order shipping costs.

orderDiscount

Optional number Order discount amount.

Example of usage:

_paq.push(["trackEcommerceOrder", "3352", 499, 399, 0, 100]);

Updating cart

To update the user cart (when the user adds new products or removes them from cart) use the trackEcommerceCartUpdate function:

_paq.push(["trackEcommerceCartUpdate", cartAmount]);
cartAmount

Required number Cart amount (sum of products).

Warning

Before updating the tracking cart, be sure to add all products in the cart by using addEcommerceItem first (including the ones that were previously in the cart). Then, use this function.

Example of usage:

_paq.push(["trackEcommerceCartUpdate", 250]);

Tracking product / category view

If you wish to track when the user enters the product site or is browsing products category, use the setEcommerceView function:

_paq.push(["setEcommerceView", productSKU, productName, productCategory, productPrice]);
productSKU

Required string/boolean Product stock-keeping unit. False for tracking category.

productName

Optional string/boolean Product name. False for tracking category.

productCategory

Optional Array<string>|string Product category, can be written as Array with up to 5 elements.

productPrice

Optional number Product price.

Warning

Product SKU, names and categories should be URL encoded.

Example of usage:

_paq.push(["setEcommerceView", "craft-311", "Unicorn Iron on Patch", "Crafts & Sewing", 499]);

Custom Variables

Deprecated since version 5.5: We strongly advise using custom dimensions instead.

Adding / Editing Custom Variable

To set a custom variable that can be used later, use the setCustomVariable function:

_paq.push(["setCustomVariable", index, name, value, scope]);
index

Required number Index from 1 to 5 where the variable is stored

name

Required string Name of the variable

value

Optional string Value of the variable limited to 200 characters.

scope

Optional string Scope of the variable, “visit” or “page”. The default value is "visit"

Note

A Custom Variable with the scope set on “visit” will be saved for visit, you don’t need to save it for every page.

Warning

Index is separate for each variable scope.

Example of usage:

_paq.push(["setCustomVariable", 1, "AspectRatio", "16:9", "visit"]);

Removing Custom Variable

To remove the custom variable, you can use the deleteCustomVariable function:

_paq.push(["deleteCustomVariable", index, scope]);
index

Required number Index from 1 to 5 where the variable is stored

scope

Optional string Scope of the variable, “visit” or “page”. The default value is "visit"

Example of usage:

_paq.push(["deleteCustomVariable", 1, "visit"]);

Accessing Custom Variable

You can access custom variables by providing a function that will use the getCustomVariable function:

_paq.push([ function() {
    var customVariable = this.getCustomVariable(index, scope );
}]);
getCustomVariable(index[, scope])
Arguments:
  • index (number) – Required Number from 1 to 5 where variable is stored
  • scope (string) – Optional Scope of the variable, “visit” or “page”. Default value is "visit"

Example of usage:

_paq.push([ function() {
    var customVariable = this.getCustomVariable(1, "visit" );
    console.log(customVariable);
}]);

Custom Dimensions

Tracking Custom Dimension

If you wish to set a custom dimension to use it in tracking functions, use the setCustomDimensionValue function:

_paq.push(["setCustomDimensionValue", customDimensionID, customDimensionValue]);
customDimensionID

Required number ID of dimension

customDimensionValue

Required string Value of Custom Dimension - limited to 255 characters.

Warning

When you set a Custom Dimension, its value will be used in all tracking requests within a page load.

Warning

This function does not send any data to the Analytics. It prepares a Custom Dimension to be sent with following events (e.g. page view, ecommerce events, outlink or download events).

Example of usage:

_paq.push(["setCustomDimensionValue", 3, "loginStatus"]);

Tracking Custom Dimension (legacy)

Deprecated since version 15.3: Function setCustomDimension() is deprecated due to difficulty of use (passed values should be URL encoded). Please use setCustomDimensionValue() instead.

If you wish to set a custom dimension to use it in tracking functions, use the setCustomDimension function:

_paq.push(["setCustomDimension", customDimensionID, customDimensionValue]);
customDimensionID

Required number ID of dimension

customDimensionValue

Required string Value of Custom Dimension - limited to 255 characters. The value provided to the function should be URL encoded.

Warning

When you set a Custom Dimension, that value will be used in all tracking requests within a page load.

Warning

This function does not send any data to the Analytics. It sets a Custom Dimension to be sent with following events (e.g. page view, ecommerce events, outlink or download events).

Example of usage:

_paq.push(["setCustomDimension", 3, "loginStatus"]);

Retrieving Custom Dimension

You can access custom dimension by providing a function that will use the getCustomDimensionValue function:

_paq.push([ function() {
    var customDimension = this.getCustomDimensionValue(index);
}]);
getCustomDimensionValue(index)
Arguments:
  • index (number) – Required Index of custom dimension

Example of usage:

_paq.push([ function() {
    var customDimension = this.getCustomDimensionValue(1);
    console.log(customDimension);
}]);

Retrieving Custom Dimension (legacy)

Deprecated since version 15.3: Function getCustomDimension() is deprecated due to the difficulty of use (returned values should be URL encoded). Please use getCustomDimensionValue() instead.

You can access custom dimension by providing a function that will use the getCustomDimension function:

_paq.push([ function() {
    var customDimension = this.getCustomDimension(index);
}]);
getCustomDimension(index)
Arguments:
  • index (number) – Required Index of custom dimension

Example of usage:

_paq.push([ function() {
    var customDimension = this.getCustomDimension(1);
    console.log(customDimension);
}]);

Content Tracking

Content Tracking tracks how many times specific elements were rendered/visible. It can be used to measure if the ad placement was visible or if the user saw the end of an article.

To track content, it has to have the data-track-content attribute or piwikTrackContent CSS class attached to it.

Tracking all content impressions within a page

To track all content impression, you can use the trackAllContentImpressions function. If this function is invoked multiple times, it will not send duplicated data unless the trackPageView was used between invocations:

_paq.push(["trackAllContentImpressions"]);

Tracking all visible content impressions

To track all visible content impressions you can use the trackVisibleContentImpressions function.

Code:

_paq.push(["trackVisibleContentImpressions", checkOnScroll, watchInterval]);
checkOnScroll

Optional boolean If true, it will check new visible content impressions on the scroll event. Default: true.

Note

It will not detect content blocks placed in a scrollable element.

watchInterval

Optional number Interval, in milliseconds between checking for new visible content. Periodic checks can be disabled for performance reasons by setting 0. Default value: 750.

Warning

Both options cannot be changed after the initial setup.

Example of usage:

_paq.push(["trackVisibleContentImpressions", true]);

Example of usage:

_paq.push(["trackVisibleContentImpressions", false, 500]);

Tracking only content impressions for specific page part

To track impressions on part of a webpage that will be populated after a page load, you can use the trackContentImpressionsWithinNode:

_paq.push(["trackContentImpressionsWithinNode", domNode]);
domNode

Required domNode DOM element that will have impression DOM elements with data-track-content attribute

It can be used with trackVisibleContentImpressions to track only visible content impressions

Example of usage:

var element = document.querySelector("#impressionContainer");
_paq.push(["trackContentImpressionsWithinNode", element]);

Track interactions manually with auto detection

If you wish to trigger an interaction manually (for example on click event), you can do it using trackContentInteractionNode, just add this code in the action you want to track:

_paq.push(["trackContentInteractionNode", domNode, contentInteraction]);
domNode

Required domNode Node marked as content block or containing content blocks. If no content block is found - nothing will be tracked.

contentInteraction

Optional string Name of interaction (e.g. "click"). Default value: "Unknown".

Example of use

<button onClick="function(){_paq.push(['trackContentInteractionNode', this, 'clicked']);}">Click me!</button>

Track impression manually

If you wish to trigger tracking impressions entirely manually, you can use the trackContentImpression:

_paq.push(["trackContentImpression", contentName, contentPiece, contentTarget]);
contentName

Required string Name of Content Impression

contentPiece

Required string Name of Content Impression Piece

contentTarget

Required string URL of Content Impression Target

Example of use:

_paq.push(["trackContentImpression", "trackingWhitepaper", "document", "http://cooltracker.tr/whitepaper"]);

Track user interaction manually

If you wish to trigger tracking interactions entirely manually, you can use the trackContentInteraction. Use it as a function inside listener on event:

_paq.push(["trackContentInteraction", contentInteraction, contentName, contentPiece, contentTarget]);
contentInteraction

Required string Name of interaction (e.g. "click").

contentName

Required string Name of Content Impression

contentPiece

Required string Name of Content Impression Piece

contentTarget

Required string URL of Content Impression Target

Example of use:

_paq.push(["trackContentImpression", "clicked", "trackingWhitepaper", "document", "http://cooltracker.tr/whitepaper"]);

Warning

Use this function in conjunction with trackContentImpression, as it can only be mapped with an impression by linking contentName. It does not map automatically as trackContentInteractionNode.

User ID Management

User ID enables merging user data that is collected between many devices and browsers.

Setting UserId

You must provide unique user-id for every user. To set user ID for tracked data use setUserId function:

_paq.push(["setUserId", userID]);
userID

Required string Unique, non-empty permanent ID of the user in application.

Reset UserId

When UserId becames unavailable anymore (eg. user logged out) you may clean the value out with resetUserId function:

_paq.push(["resetUserId"]);

Miscellaneous

Custom page name

We are using the current page URL as the page title. To change this use the setDocumentTitle function:

_paq.push(["setDocumentTitle", title]);
title

Required string Title to show instead of URL

Example of usage:

_paq.push(["setDocumentTitle", document.title]);

Measuring user time spent on web page

When the user will visit only one page during a session, we will assume that his total time spent on the website was 0 ms. To measure session time more accurately you can use the enableHeartBeatTimer function:

_paq.push(["enableHeartBeatTimer"]);

Example of usage:

_paq.push(["enableHeartBeatTimer"]);

Note

First heart beat will be sent after 15 seconds and each heart beat following it will sent with longer and longer intervals (up to 5 minute ceiling). When page will loose focus, heart beats will be paused until focus is restored. Heart beats will stop after 30 minutes from last page view.

Tracking internal searches

To track search requests on your site use the trackSiteSearch function:

_paq.push(["trackSiteSearch", keyword, category, searchCount, dimensions]);
keyword

Optional string Keyword that was searched

category

Optional string Category seleted in search engine - you can set it to false when not used.

searchCount

Optional number Results on the results page - you can set it to false when not used.

dimensions

Optional object Custom dimension that should be tracked with this action. Can be multiple dimensions. Written as object property using dimension{ID} notation.

Example:

{
   dimension1: "example value",
   dimension2: "example value"
}

Example of usage:

_paq.push(["trackSiteSearch", "test", false, 20]);

Tracking user anonymously

To track visitor anonymously (without consent) use the setUserIsAnonymous function:

_paq.push(["setUserIsAnonymous", isAnonymous]);
isAnonymous

Required boolean Flag that sets anonymous tracking on and off

Example of usage:

_paq.push(["setUserIsAnonymous", true]);

To disable tracking user anonymously (after visitor gave consent) use deanonymizeUser function:

_paq.push(["deanonymizeUser"]);

Send ping request on demand

Ping method sends request that will update session values without creating new event or page view. Most common use for this method is update of session custom dimensions or custom variables.

Example of usage:

_paq.push(["ping"]);

Gathering navigation timing page performance metrics

To set up page performance metrics gathering use the setTimingDataSamplingOnPageLoad function:

_paq.push(["setTimingDataSamplingOnPageLoad", updateTimingDataOnPageLoadSampling]);
updateTimingDataOnPageLoadSampling

Required integer Value between 1 and 100 describing the percentage for data sampling

It sets another request triggered onLoad, after trackPageView setting timing data. Normally we try to use trackPageView as soon as possible, not to lose any actions but since it’s usually before the full page was loaded then we don’t have complete data about timing. You may either trigger trackPageView after onLoad event or enable this option so the followup request containing all timing values is sent after onLoad.

Argument to this function represents data sampling percentage (with possible integer values between 0 and 100).

Example of usage:

_paq.push(["setTimingDataSamplingOnPageLoad", 0]); // disables timing data collection
_paq.push(["setTimingDataSamplingOnPageLoad", 5]); // this is the default setting, uses 5% data sampling
_paq.push(["setTimingDataSamplingOnPageLoad", 30]); // enables 30% data sampling (only around 30% of all tracked actions will collect timing data if possible)
_paq.push(["setTimingDataSamplingOnPageLoad", 100]); // enables 100% data sampling (which means that all tracked actions will collect timing data if possible)

Note

In order for this setting to make effect setTimingDataSamplingOnPageLoad() should be used before the trackPageView() function

Note

If enabled, timing data is collected only when page view lasted longer than the time it takes the page to load no partial information is stored, all metrics or nothing