Go Back

JavaScript tracking client

January 30, 2018

This document’s purpose is to show how you can expand, change or build anew the standard Piwik PRO JavaScript tracking code.

Methods displayed below require some programming knowledge and can break your tracking if not used properly so always backup your work, and don’t test your new solutions on production environment!

Tracking API methods

Requesting additional tracker object.

  • Piwik.getTracker( trackerUrl, siteId ) – Returns new Piwik PRO tracker instance.
  • Piwik.getAsyncTracker(optionalTrackerUrl, optionalTrackerSiteId) – Returns a new asynchronous instance of Piwik PRO tracker.

Tracker methods

  • trackEvent(category, action, [name], [value]) – Tracks a custom event for a chosen category and an action (mandatory). Can also optionally contain a name and a value.
  • trackPageView([customTitle]) – Logs a pageview, can optionally contain a custom Page Title. This method is especially important as it often is required to pass additional data to Piwik PRO
  • trackSiteSearch(keyword, [category], [resultsCount]) – Logs a site search keyword, optionally can also log search category and number of returned results.
  • trackGoal( idGoal, [customRevenue]); – Logs a conversion of a goal with the provided ID , can also send a revenue for of the conversion (optional).
  • trackLink( url, linkType ) – Log a link click. Provide a URL to which a click leads and a type of the click (either a ‘link’ or a ‘download’).
  • trackAllContentImpressions() – This method searches the whole DOM, looking for content blocks and impressions, tracking them, after the DOM is ready.
  • trackVisibleContentImpressions ( checkOnScroll, timeIntervalInMs ) – Searches the DOM for content blocks, but tracks only the ones that are actually displayed.
  • trackContentImpressionsWithinNode( domNode ) – Searches selected DOM node and it’s children looking for content blocks tracking impressions for them provided that they were not traced before.
  • trackContentInteractionNode( domNode, contentInteraction ) – Manually track an interaction in the provided DOM node or content block.
  • trackContentImpression( contentName, contentPiece, contentTarget ) – Manually track a content impression with the provided name, piece and target.
  • trackContentInteraction( contentInteraction, contentName, contentPiece, contentTarget ) – Manually track a content interaction with the provided intercaction, name, piece and target.
  • logAllContentBlocksOnPage – Logs all content blocks present on a page to the console. Useful for debugging
  • enableLinkTracking( enable ) – Enables tracking of links allowing tracking both, left clicks as middle and right clicks (via context menus).
  • enableHeartBeatTimer( delayInSeconds ) – Enables accurate visit time tracking by forcing Piwik PRO to ‘ping’ the server every 15 seconds of visit ( the interval can be adjusted by providing the number of seconds as parameter).
  • enableCrossDomainLinking() – Enables cross domain linking. The visitor ID’s, identifying unique visitors, are by default stored as a first party cookie in the visitors browser – meaning that such cookie can only be accessed from the domain it was created on. If you want to track visit across multiple domain, you should enable this option. It will pass a pk_vid parameter in the URL whenever a visitor will click a link to a different domain.
  • setCrossDomainLinkingTimeout( timeout ) – Change the timeout within which two clicks across the domains will be connected as a single visit.

Tracker object configuration

  • setDocumentTitle( string ) – Manually set the title of current page.
  • setDomains( array) – Set array of hostnames or domains to be treated as local. For wildcard subdomains, you can use: setDomains('.example.com'); or setDomains('*.example.com');. You can also specify a path along a domain: setDomains('*.example.com/subsite1');
  • setCustomUrl( string ) – Manually set the URL of the current page.
  • setReferrerUrl( string ) – Manually set the referrer of the visit.
  • setSiteId( integer ) – Set the SiteID parameter. Redundant: can be specified in getTracker() constructor.
  • setTrackerUrl( string ) – Set the Piwik PRO server URL. Redundant: can be specified in getTracker() constructor.
  • getPiwikUrl – Returns the Piwik PRO server URL.
  • getCurrentUrl – Return URL of currentl tracked page (actual URL or custom one if it was set)
  • setDownloadClasses( string | array ) – Set classes to be considered as downloads.
  • setDownloadExtensions( string | array ) – Set list of file extensions to be considered as downloads. Example: ‘doc’ or [‘doc’, ‘xls’]
  • addDownloadExtensions( string | array ) – Specify additional file extensions to be considered as downloads. Example: ‘doc’ or [‘doc’, ‘xls’]
  • removeDownloadExtensions( string | array ) – Remove extensions from the list of download file extensions. Example: ‘doc’ or [‘doc’, ‘xls’]
  • setIgnoreClasses( string | array ) – Set classes to be ignored if present in link
  • setLinkClasses( string | array ) – Set classes to be considered as outlinks
  • setLinkTrackingTimer( integer ) – Set delay for the link tracking in milliseconds.
  • getLinkTrackingTimer – Returns the delay for link tracking (in milliseconds).
  • discardHashTag( bool ) – Set to true to ignore parts of URL after the anchor (# – hashtag)
  • setGenerationTimeMs(generationTime) – Overwrite the standard generation time (taken from the browser DOM Timing) with your own value.
  • appendToTrackingUrl(appendToUrl) – Append a custom string to the end of the HTTP request to piwik.php?
  • setDoNotTrack( bool ) – If set to true, browsers with Do Not Tracked preference will be ignored.
  • killFrame() – Enables a frame-buster preventing the tracked web page from being framed/iframed.
  • redirectFile( url ) – Forces the browser load the live URL if the tracked web page is loaded from a local file.
  • setHeartBeatTimer( minimumVisitLength, heartBeatDelay ) – reguralry sends requests to Piwik PRO server to accurately record how long the page has been viewed.
  • getVisitorId() – returns the 16 characters ID for the visitor
  • getVisitorInfo() – returns the visitor cookie contents as an array
  • getAttributionInfo() – returns the array of visitor attribution.

To get specific attributes of attribution try following methods:

* piwikTracker.getAttributionCampaignName()
* piwikTracker.getAttributionCampaignKeyword()
* piwikTracker.getAttributionReferrerTimestamp()
* piwikTracker.getAttributionReferrerUrl()

  • getUserId() – returns the User ID string provided it is present.
  • setUserId( userId ) – Sets a for the current user.
  • setCustomVariable (index, name, value, scope) – Sets a custom variable.
  • deleteCustomVariable (index, scope) – Deletes a custom variable.
  • getCustomVariable (index, scope) – Retrieves a custom variable.
  • storeCustomVariablesInCookie() – Stores the Custom Variable with the scope “visit” in a first party cookie.
  • setCustomDimension (customDimensionId, customDimensionValue) – Sets a custom dimension.
  • deleteCustomDimension (customDimensionId) – Deletes a custom dimension.
  • getCustomDimension (customDimensionId) – Retrieves a custom dimension.
  • setCampaignNameKey(name) – Sets campaign name parameter(s).
  • setCampaignKeywordKey(keyword) – Sets campaign keyword parameter(s).
  • setConversionAttributionFirstReferrer( bool ) – Switches the conversion attribution to the first refferer (by default it is attributed to the last one)

Ecommerce

Piwik PRO comes with an abilty to track tranbsactions on ecommerce sites to learn more about the visit thir article

  • setEcommerceView( productSKU, productName, categoryName, price ) – Sets the current page view as an ecommerce view (view of product or category page). it has to be followed by the trackPageView to record the product or category page view.
  • addEcommerceItem( productSKU, [productName], [productCategory], [price], [quantity] ) – Adds a product into the cart. Needs to be called for each product in the order.
  • trackEcommerceCartUpdate( grandTotal ) – Tracks a shopping cart update. Shuld be called after every time a user is adding, updating or deleting a product from the cart.
  • trackEcommerceOrder( orderId, grandTotal, [subTotal], [tax], [shipping], [discount] ) – Tracks an Ecommerce order. This represents an actual sale and shuld be called at the end of the transaction.

Tracking Cookies Configuration

  • disableCookies() – Disables all of the first party cookies. Next pageview will ensure that all currently stored cookies will be deleted.
  • deleteCookies() – Removes all of the currently stored Piwik PRO cookies.
  • hasCookies() – Boolean, returning true if cookies can be set in the browser.
  • setCookieNamePrefix( prefix ) – change the cookie prefix from the defaul ‘_pk_’.
  • setCookieDomain( domain ) – change the default (document domain) cookie domain.
  • setCookiePath( path ) – the default is ‘/’.
  • setSecureCookies( true ) – enable to add a secure cookie flag to all of the first party cookies. This safety measurement should be used on all HTTPS websites to ensure that all of the cookies are sent only via HTTPS.
  • setVisitorCookieTimeout( seconds ) – Alters the default 13 month lifetime
  • setReferralCookieTimeout( seconds ) – Alters the default 6 months lifetime
  • setSessionCookieTimeout( seconds ) – Alters the default 30 minutes lifetime

Advanced uses

  • addListener( element ) – Add click listener to a chosen link element. When clicked. Will cause Piwik PRO to automatically log the click after the element is clicked.
  • setRequestMethod( method ) – Sets the request method to “GET” or “POST” – GET being the default one. The POST method can only be used if both Piwik PRO and the tracked website are on the same server.
  • setCustomRequestProcessing( function ) – Enables a content-request processing function that will be fired whenever query parameters strings are prepared, but before before the request is sent.
  • setRequestContentType( contentType ) – Creates a header with Content-Type. It should be used with the setRequestMethod set to “POST”.

Summary

Although the above methods may seem to be ver complicated, most of them can be easily combined with the standard Piwik PRO tracking code – especially when using Piwik PRO Tag Manager!

If you have any questions regarding using the above methods, feel free to contact our support team at support@piwik.pro