Tracker Object Functions

This document describes all the functions available for the Tracker object and how to create its instances. This enables users to track multiple Trackers at once.

Accessing Tracker Object

To access Tracker object instance you must use the Piwik.getTracker function

Piwik.getTracker(trackerUrl, siteId)

Getter for Analytics Tracker instance.

Arguments:
  • trackerUrl (string) – Required URL for Tracker
  • siteId (string) – Required Site ID that will be linked to tracked data.
Returns:

Analytics Tracker instance

To access internal instance of the Tracker used for asynchronous tracking you must use the Piwik.getAsyncTracker function

Piwik.getAsyncTracker(trackerUrl, siteId)

Getter for Analytics Tracker instance.

Arguments:
  • trackerUrl (string) – Required URL for Tracker
  • siteId (string) – Required Site Id that will be linked to tracked data.
Returns:

Analytics Tracker instance

Tracking functions

trackPageView([customPageTitle])

Tracks a visit on the page that the function was run on.

Arguments:
  • customPageTitle (string) – Optional Custom page title, for example document.title
trackEvent(category, action[, name, value])

Tracks events that should not trigger on page loading, but only when user performs an action

Arguments:
  • category (string) – Required Category of event.
  • action (string) – Required Event action, for example "link click".
  • name (string) – Optional Event name, for example "Cancel button".
  • value (number) – Optional Event value.
trackGoal(idGoal[, customRevenue, customData])

Manually tracks goal (conversion).

Arguments:
  • idGoal (int/string) – Required Id of goal.
  • customRevenue (int/float) – Optional Revenue value
  • customData (mixed) – Optional Object with Custom dimensions.
trackSiteSearch(keyword[, category, resultCount])

The function that tracks internal site searches.

Arguments:
  • keyword (string) – Required String containing keyword that was searched.
  • category (string/boolean) – Optional String with category selected in search engine, can set it to false when not used.
  • searchCount (number/boolean) – Optional Number of results on the results page, can be set to false when not used.
enableHeartBeatTimer()

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

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.

enableCrossDomainLinking()

The function that will enable cross domain linking. That way visitors across domains will be linked.

setCrossDomainLinkingTimeout(timeout)

The function will change default time in which two visits across domains will be linked.

Arguments:
  • timeout (number) – Required Time in seconds in which two visits across domains will be linked. Default is 180.
getCrossDomainLinkingUrlParameter()

Returns the query parameter that can be appended to link URLs so cross domain visits can be detected. If your application creates links dynamically, then you’ll have to add this query parameter manually to those links (since the JavaScript tracker cannot detect when those links are added).

Eg:

var url = 'http://myotherdomain.com/?' + piwikTracker.getCrossDomainLinkingUrlParameter(); $element.append('<a href="' + url + '"/>');

Ecommerce tracking

addEcommerceItem(productSKU[, productName, productCategory, price, quantity])

The function that adds ecommerce item, can be used when adding and removing items from cart.

Arguments:
  • productSKU (string) – Required String with product stock-keeping unit.
  • productName (string) – Optional String with product name.
  • productCategory (Array<string>|string) – Optional Product category, can be written as Array with up to 5 elements.
  • price (string) – Optional String with product price.
  • quantity (string) – Optional String with product quantity.
removeEcommerceItem(productSKU)

The function that removes ecommerce item, can be used when removing items from cart.

Arguments:
  • productSKU (string) – Required String with product stock-keeping unit.
clearEcommerceCart()

The function that clears all ecommerce items, can be used when cart is deleted.

getEcommerceItems()

The function that returns all ecommerce items, can be used to check state of tracked cart.

Response example:

{“craft-311”:[“craft-311”,”Unicorn Iron on Patch”,”Crafts & Sewing”,”499”,”3”]}
Returns:Object containing all tracked items (format: Object<productSKU, Array[productSKU, productName, productCategory, price, quantity]>).
trackEcommerceOrder(orderId, orderGrandTotal[, orderSubTotal, orderTax, orderShipping, orderDiscount])

The function that tracks Ecommerce order, also tracks all items previously added.

Arguments:
  • orderId (string) – Required Unique order ID.
  • orderGrandTotal (number) – Required Order Revenue grand total - tax, shipping and discount included.
  • orderSubTotal (number) – Optional Order subtotal - without shipping.
  • orderTax (number) – Optional Order tax amount.
  • orderShipping (number) – Optional Order shipping costs.
  • orderDiscount (number) – Optional Order discount amount.
trackEcommerceCartUpdate(grandTotal)

The function that tracks the shopping cart value. Use this each time there is a change in cart as the last function after adding cart items.

Arguments:
  • grandTotal (number) – Required Order Revenue grand total - tax, shipping and discount included.
setEcommerceView(productSKU[, productName, productCategory, productPrice])

The function to track product or category page view, must be followed by the trackPageView function.

Arguments:
  • productSKU (string) – Required String with product stock-keeping unit.
  • productName (string) – Optional String with product name.
  • productCategory (Array<string>|string) – Optional Product category, can be written as Array with up to 5 elements.
  • price (string) – Optional String with product price.

Custom variables

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

setCustomVariable(index, name, value, scope)

The function that sets a custom variable to be used later.

Arguments:
  • index (string) – Required Number from 1 to 5 where variable is stored.
  • name (string) – Required Name of the variable.
  • value (string) – Required Value of the variable.
  • scope (string) – Required Scope of the variable, "visit" or "page".
deleteCustomVariable(index, scope)

The function that will delete a custom variable.

Arguments:
  • index (string) – Required Number from 1 to 5 where variable is stored.
  • scope (string) – Required Scope of the variable, "visit" or "page".
getCustomVariable(index, scope)

The function that will return the value of custom variable.

Arguments:
  • index (string) – Required Number from 1 to 5 where variable is stored.
  • scope (string) – Required Scope of the variable, "visit" or "page".
storeCustomVariablesInCookie()

The function will enable storing "visit" type custom variables in a first party cookie. That will enable getting them via the getCustomVariable function.

Custom dimensions

setCustomDimensionValue(customDimensionId, customDimensionValue)

New in version 15.3.

The function that sets a custom dimension to be used later.

Arguments:
  • customDimensionId (string) – Required Id of custom dimension.
  • customDimensionValue (string) – Required Value of custom dimension.
setCustomDimension(customDimensionId, customDimensionValue)

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

Function that sets a custom dimension to be used later.

Arguments:
  • customDimensionId (string) – Required Id of custom dimension.
  • customDimensionValue (string) – Required Value of custom dimension (value should be URL encoded).
deleteCustomDimension(customDimensionId)

The function that will delete a custom dimension.

Arguments:
  • customDimensionId (string) – Required Id of custom dimension.
getCustomDimensionValue(customDimensionId)

New in version 15.3.

The function that will return the value of custom dimension.

Arguments:
  • customDimensionId (string) – Required Id of custom dimension.
Returns:

Value set with setCustomDimensionValue()

Return type:

string

getCustomDimension(customDimensionId)

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.

The function that will return the value of custom dimension.

Arguments:
  • customDimensionId (string) – Required Id of custom dimension.
Returns:

Value set with setCustomDimension()

Return type:

string

Content Tracking

Impressions

trackAllContentImpressions()

The function that will scan DOM for content blocks and tracks impressions after all page will load.

trackVisibleContentImpressions([checkOnScroll, watchInterval])

The function that will scan DOM for all visible content blocks and will track these impressions.

Arguments:
  • checkOnScroll (boolean) – Optional Enables tracking content blocks that will be visible after scroll event.
  • watchInterval (number) – Optional Interval, in milliseconds between checking for new visible content. Periodic checks can be disabled for performance reasons by setting 0. Default value: 750.
trackContentImpressionsWithinNode(domNode)

The function that will scan domNode (with its children) for all content blocks and will track impressions.

Arguments:
  • domNode (domNode) – Required DOM node with content blocks (with data-track-content attribute) inside.
trackContentImpression(contentName, contentPiece, contentTarget)

The function that manually tracks content impression.

Arguments:
  • contentName (string) – Required String containing name of Content Impression.
  • contentPiece (string) – Required String containing name of Content Impression Piece.
  • contentTarget (string) – Required String containing URL of Content Impression Target.
logAllContentBlocksOnPage()

The function that will print all content blocks in the console for debugging purposes.

Interactions

trackContentInteractionNode(domNode[, contentInteraction])

The function that tracks interaction within domNode. This can be used as a function inside the onClick attribute.

Arguments:
  • domNode (domNode) – Required Node marked as content block or containing content blocks. If no content block will be found - nothing will be tracked.
  • contentInteraction (string) – Optional Name of interaction (e.g. "click"). Default value: "Unknown".
trackContentInteraction(contentInteraction, contentName, contentPiece, contentTarget)

The function that tracks content interaction using the given data.

Arguments:
  • contentInteraction (string) – Required Name of interaction (e.g. "click").
  • contentName (string) – Required Name of Content Impression.
  • contentPiece (string) – Required Name of Content Impression Piece.
  • contentTarget (string) – Required URL of Content Impression Target.

User ID and Visitor ID Management

User ID

getUserId()

The function that will return user ID.

setUserId(userId)

The function that will set user ID to this user.

Arguments:
  • userId (string) – Required Unique, non-empty string preserved for each user.
resetUserId()

The function that will reset user ID value.

Visitor ID

getVisitorId()

The function that will return 16 characters ID for the visitor.

getVisitorInfo()

The function that will return visitor information in an array:

  • new visitor flag indicating new (1) or returning (0) visitor
  • visitor ID (UUID)
  • first visit timestamp (Unix epoch time)
  • previous visit count (0 for first visit)
  • current visit timestamp (Unix epoch time)
  • last visit timestamp (Unix epoch time or '' if N/A)
  • last e-commerce order timestamp (Unix epoch time or '' if N/A)

Tracking cookies management

Cookies that are used by analytics are first party cookies.

disableCookies()

The function that will disable all first party cookies. Existing ones will be deleted in the next page view.

enableCookies()

The function that will enable all first party cookies. Cookies will be created on first sent tracking request.

Note

Tracker has cookies enabled by default.

deleteCookies()

The function that will delete existing tracking cookies after the next page view.

hasCookies()

The function that will return true if cookies are enabled in this browser.

setCookieNamePrefix(prefix)

The function that will set the prefix for analytics tracking cookies. Default is "_pk_"

Arguments:
  • prefix (string) – Required String that will replace default analytics tracking cookies prefix.
setCookieDomain(domain)

The function that will set the domain for the analytics tracking cookies.

Arguments:
  • domain (string) – Required Domain that will be set as cookie domain. For enabling subdomain you can use wildcard sign or dot.
setCookiePath(path)

The function that will set the analytics tracking cookies path.

Arguments:
  • path (string) – Required Path that will be set, default is "/"
setSecureCookie(bool)

The function that will toggle the Secure cookie flag on all first party cookies (if you are using HTTPS).

Arguments:
  • bool (boolean) – Required If set to true it will add Secure cookie flag.
setVisitorCookieTimeout(seconds)

The function that will set the expiration time of visitor cookies.

Arguments:
  • seconds (number) – Required Seconds after which the cookie will expire. Default is 13 months.
setReferralCookieTimeout(seconds)

The function that will set the expiration time of referral cookies.

Arguments:
  • seconds (number) – Required Seconds after which the cookie will expire. Default is 6 months.
setSessionCookieTimeout(seconds)

The function that will set the expiration time of session cookies.

Arguments:
  • seconds (number) – Required Seconds after which the cookie will expire. Default is 30 minutes.
setVisitorIdCookie()

The function that will set cookie containing analytics ID.

Note

It’s needed only when tracker instance is created without use of _paq.push() and script needs to know analytics ID before first tracking request is sent. Make sure that it is called after all methods that configure cookie are called (e.g. setCookieNamePrefix(), setCookieDomain(), setCookiePath(), etc.).

Tracker Configuration

setDocumentTitle([title])

The function that will set the document tile that is being sent with tracking data.

Arguments:
  • title (string) – Optional String that will override default document.title
setDomains(domains)

The function that will set an array of domains to be treated as local. Sub-domain wildcards are supported (e.g. *.example.com).

Arguments:
  • domains (array<string>) – Required Array of hostnames written as strings.
setCustomUrl(customUrl)

The function that will override tracked page URL. Tracker will use current page URL if custom URL was not set.

Arguments:
  • customUrl (string) – Required Value that will override default URL.
setReferrerUrl(url)

The function that will override the detected HTTP referrer.

Arguments:
  • url (string) – Required Value that will override HTTP referrer.
setApiUrl(url)

The function that will set the Analytic’s HTTP API URL endpoint. Usually the root directory of analytics.

Arguments:
  • url (string) – Required Path to Analytic’s HTTP API URL
getPiwikUrl()

The function that will return the Analytic’s server URL.

getCurrentUrl()

The function that will return the current URL of the page. The custom URL will be returned if set.

discardHashTag(enableFilter)

The function that will set tracker to include or remove URL fragment identifier from tracked URLs.

Arguments:
  • enableFilter (boolean) – Required If set to true, URL fragment identifier will be removed from tracked URLs.
setGenerationTimeMs(generationTime)

The function that overrides DOM Timing API provided time needed to download the page.

Arguments:
  • generationTime (number) – Required Time that will take to download page, in milliseconds.
appendToTrackingUrl(appendToUrl)

The function that will append a custom string to the tracking URL.

Arguments:
  • appendToUrl (string) – Required String that will be added to the tracking URL.
setDoNotTrack(enable)

The function that will disable tracking users who set the Do Not Track setting.

Arguments:
  • enable (boolean) – Required When set to true tracking wont occur.
killFrame()

The function that will block a site from being iframed.

redirectFile(url)

The function that will force the browser to load URL if the tracked web page was saved as a file.

Arguments:
  • url (string) – Required URL that should be loaded.
setCampaignNameKey(name)

The function that will set campaign name parameters.

Arguments:
  • name (string) – Required Campaign name.
setCampaignKeywordKey(keyword)

The function that will set campaign keyword parameters.

Arguments:
  • keyword (array<string>) – Required Keyword parameters.

Anonymization

setUserIsAnonymous(isAnonymous)

The function that will set user anonymous tracking.

Arguments:
  • isAnonymous (boolean) – Required Flag that sets anonymous tracking on and off.
deanonymizeUser()

The function that will disable user anonymous tracking and send deanonymization request.

Advanced Usage

ping()

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.

addListener(domElement)

The function will add a click listener to link element.

Arguments:
  • domElement (DOMElement) – Required Element that click will trigger logging the click automatically.
setRequestMethod(method)

The function that will set the request method.

Arguments:
  • method (string) – Required Method that will be used in requests. "GET" or "POST" are supported. The default is "GET"
setCustomRequestProcessing(function)

The function that will process the request content. The function will be called once the request (query parameters string) has been prepared, and before the request content is sent.

setRequestContentType(contentType)

The function that will set tracking requests Content-Type header. Used when tracking uses the "POST" method (set by setRequestMethod).

Arguments:
  • contentType (string) – Required Content-Type value to be set.
customCrossDomainLinkDecorator(urlDecorator)

The function that set custom cross domain decorator used on links to pass visitor ID via URL (used by enableCrossDomainLinking()). It will be later parsed by customCrossDomainLinkVisitorIdGetter().

Arguments:
  • urlDecorator (function) – function that will decorate URL with visitor ID passed by URL
urlDecorator(url, value, name)

Decorator function accepts link URL and visitor ID value and parameter name and returns URL containing visitor ID data.

Arguments:
  • url (string) – Required Link URL
  • value (string) – Required Value of visitor ID that should be passed via URL
  • name (string) – Required Name of visitor ID parameter used by tracker (can be set)
Returns:

Decorated URL or null (no change in URL)

Return type:

string|null

Note

Usage example: value send via URL query parameter (equivalent of default implementation).

_paq.push(['customCrossDomainLinkDecorator', function(url, value, name) {
    var parsedUrl = new URL(url);
    parsedUrl.searchParams.append(name, value);
    return parsedUrl.href;
}]);
customCrossDomainLinkVisitorIdGetter(urlParser)

The function that set custom cross domain URL parser (decorated by function set via customCrossDomainLinkDecorator()). It returns value of visitor ID parsed from page URL (used by enableCrossDomainLinking()).

Arguments:
  • urlParser (function) – function that will parse URL and return value of visitor ID passed through it.
urlParser(url, name)

Parser function that accepts page URL and visitor ID parameter name and returns visitor ID value.

Arguments:
  • url (string) – Required page URL
  • name (string) – Required name of visitor ID param used by tracker (can be set)
Returns:

Visitor ID value (parsed from URL)

Return type:

string

Note

Usage example: value send via URL query parameter (equivalent of default implementation).

_paq.push(['customCrossDomainLinkVisitorIdGetter', function(url, name) {
    return (new URL(url)).searchParams.get(name) || '';
}]);
enableJSErrorTracking()

Enables tracking of unhandled JavaScript errors

Note

Browsers may limit information about error details if it occurs in script loaded from different origin (see details).