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 (string) – 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(delay)

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

:param number delay: **Required** Time in seconds between cyclical heartbeat requests, default ``30``
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.

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>) – 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.
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 sub total - 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, categoryName, 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>) – Optional Product category, can be written as Array with up to 5 elements.
  • price (string) – Optional String with product price.

Custom variables

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

setCustomDimension(customDimensionId, customDimensionValue)

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.
deleteCustomDimension(customDimensionId)

The function that will delete a custom dimension.

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

The function that will return the value of custom dimension.

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

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.

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.

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.

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<https://en.wikipedia.org/wiki/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.
setHeartBeatTimer(minimumVisitLength, heartBeatDelay)

The function that sets how long the page has been viewed for if the minimumVisitLength is attained.

Arguments:
  • minimumVisitLength (number) – Required Minimum visit length in seconds.
  • heartBeatDelay (number) – Required Update sever time threshold.
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

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.