Docs › JavaScript tracking
Piwik comes with a very powerful Javascript Tracking API. Advanced users can use the Piwik Tracker code to customize the way some of the web analytics data is recorded in Piwik. Plugin developers can also pass custom JSON data to the piwik tracking script, and use this data in plugins.
Pre-requisite: please make sure you are using the new version of the Javascript tracking code
The basic Piwik tracking code looks like the following:
<!-- Piwik -->
<script type="text/javascript">
var pkBaseURL = (("https:" == document.location.protocol) ? "https://{$PIWIK_URL}" : "http://{$PIWIK_URL}");
document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
</script><script type="text/javascript">
try {
var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", {$IDSITE});
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
} catch( err ) {}
</script>
<!-- End Piwik Tag -->
In your Piwik tracking code, {$PIWIK_URL} would be replaced by your Piwik URL and {$IDSITE} would be replaced by the idsite of the website you are tracking in Piwik.
If your Piwik tracking code doesn't look like this one, you might be using the old deprecated version. This version would still work as expected and keep tracking your visitors. However to use all the features described in this page, you will need to use the new version of the tracking code. Please visit your Piwik Admin section, request the Javascript code for the given website, and update your pages with the new code.
Customize the page name displayed in Piwik
By default Piwik uses the URL of the current page as the page name in the Piwik interface. If your URLs are not simple, or if you want to customize the way Piwik tracks your pages, you can specify the page name to use in the JavaScript tag.
A common way is to use the HTML Title value:
[...]
piwikTracker.setDocumentTitle(document.title);
piwikTracker.trackPageView();
[...]
Advanced users can also dynamically generate the page name, for example in PHP:
[...]
piwikTracker.setDocumentTitle("<?php echo $myPageTitle; ?>");
piwikTracker.trackPageView();
[...]
Manually trigger a conversion for a Goal
By default, Goals in Piwik are defined as "matching" parts of the URL (starts with, contains, or regular expression matching). You can also by default track goals for given page views, downloads, or outlinks clicks.
In some situation, you want to register conversions on other types of actions, for example:
- when a user submits a form
- when a user has stayed more than a given amount of time on the page
- when a user does some interaction in your flash application
- when a user has submitted his cart and has done the payment: you can give the piwik tracking code to the payment website which will then register the conversions in your Piwik database, with the conversion's custom revenue
- etc.
To trigger a goal using the Piwik Javascript Tracking, you can simply do:
[...]
piwikTracker.trackGoal(1); // logs a conversion for goal 1
[...]
You can also register a conversion for this goal with a custom Revenue, for example you can generate the call to trackGoal dynamically to set the revenue of the transaction:
[...]
piwikTracker.trackGoal(1, <?php echo $cart->getCartValue(); ?>); // logs a conversion for goal 1 with the custom revenue set
[...]
Consider a host an "alias" host and not record the links to this domain as "outlinks"
By default all links to domains other than the current domain are considered outlinks. If you have multiple domains and don't want to consider links to these websites as 'outlinks' you can specify then in an array of domain names. There is a support for wildcard, if you want to ignore all clicks to subdomains of a specific domain.
[...]
piwikTracker.setDomains(["*.hostname1.com", "hostname2.com"]); // the currently tracked website is added to this array anyway
piwikTracker.trackPageView();
[...]
Disable the download & outlink tracking
By default, the Piwik Tracking code enables clicks and download tracking. To disable all the automatic download and outlink tracking, you must remove the call to the enableLinkTracking function:
[...]
// we comment out the function that enables link tracking
// piwikTracker.enableLinkTracking();
piwikTracker.trackPageView();
[...]
Disable the download & outlink tracking for specific CSS classes
You can disable automatic download and outlink tracking for links with specific CSS classes:
[...]
piwikTracker.setIgnoreClasses( "no-tracking" ); // you can also pass an array of strings
piwikTracker.trackPageView();
[...]
This will result in clicks on a link <a href='http://example.com' class='no-tracking'>Test</a> to not being counted.
Disable download or outlink tracking on a specific link
If you want to always ignore download or outlink tracking on a specific link, you can add the 'piwik_ignore' css class to it:
<a href='latest.zip' class='piwik_ignore'>File I don't want to track as a download</a>
Force a click on a link to be recorded as a download in Piwik
If you want Piwik to consider a given link as a download, you can add the 'piwik_download' css class to the link:
<a href='last.php' class='piwik_download'>Link I want to track as a download</a>
Note: you can customize and rename the CSS class used to force a click to being recorded as a download:
[...]
// now all clicks on links with the css class "download" will be counted as downloads
piwikTracker.setDownloadClasses( "download" ); // you can also pass an array of strings
piwikTracker.trackPageView();
[...]
Force a click on a link to be recorded as an outlink in Piwik
If you want Piwik to consider a given link as an outlink (links to the current domain or to one of the alias domains), you can add the 'piwik_link' css class to the link:
<a href='http://mysite.com/partner/' class='piwik_link'>Link I want to track as an outlink</a>
Note: you can customize and rename the CSS class used to force a click to being recorded as an outlink:
[...]
// now all clicks on links with the css class "external" will be counted as outlinks
piwikTracker.setLinkClasses( "external" ); // you can also pass an array of strings
piwikTracker.trackPageView();
[...]
Changing the pause timer
When a user clicks to download a file, or clicks on an outbound link, Piwik records it. In order to do so, it adds a small delay before the user is redirected to the requested file or link. We use a default value of 500ms, but you can set it to a shorter length of time. It should be noted, however, that doing so results in the risk that this period of time is not long enough for the data to be recorded in Piwik.
[...]
piwikTracker.setLinkTrackingTimer( 250 ); // 250 milliseconds
piwikTracker.trackPageView();
[...]
Changing the list of file extensions to track as "downloads"
By default, any file ending with one of these extensions will be considered a 'download' in the Piwik interface:
7z|aac|arc|arj|asf|asx|avi|bin|csv|doc|exe|flv|gif|
gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|
msp|pdf|phps|png|ppt|qtm?|ra(m|r)?|sea|sit|tar|tgz|
torrent|txt|wav|wma|wmv|wpd||xls|xml|z|zip
To replace the list of extensions you want to track as file downloads, you can:
[...]
piwikTracker.setDownloadExtensions( "jpg|png|gif" ); // we now only track clicks on images
piwikTracker.trackPageView();
[...]
If you want to track a new filename type, you can just add it to the list:
[...]
// clicks on URLs finishing by mp5 or mp6 will be counted as downloads
piwikTracker.addDownloadExtensions( "mp5|mp6" );
piwikTracker.trackPageView();
[...]
Other functions
Send custom JSON data to the piwik.php tracking scripts (plugins developers)
For example, sending user ID data in an (imaginary) user tracking plugin:
[...]
var user = { 'userId' : user_id };
piwikTracker.setCustomData( user );
piwikTracker.trackPageView();
[...]
You can also send custom data for a specific click, in the trackLink method.
For example, sending transaction data for use in an imaginary ecommerce tracking plugin.
[...]
var trans = { 'orderId' : order_id,
'storeId' : store_id,
'total' : total,
'city' : city,
'state' : state,
'country' : country,
'skus' : 'A;B;C',
'units' : '1;2;1'
};
piwikTracker.trackLink( '/store', 'addTransaction', trans );
[...]
All custom data can be set as JSON objects. The Piwik code will automatically encode the JSON object and build a string version, that you can then decode on the php side using json_decode(). We use the open source JSON implementation found on json.org.
Note: currently, the custom data is not recorded in the Piwik database. A plugin making use of the custom data would have to store the data in its own table and then archive it. If you need help building such a functionnality, please ask your question on the piwik-hackers mailing list (more info).
Multiple Piwik Trackers
It is possible to track a page using multipe Piwik trackers that point to the same or different Piwik servers. To improve page loading time, you can load piwik.js once. Each call to Piwik.getTracker() returns a unique Piwik Tracker object (instance) which can be configured.
The first parameter of the call to getTracker
<script type="text/javascript">
try {
var piwikTracker = Piwik.getTracker("http://URL_1/piwik.php", 1);
piwikTracker.trackPageView();
var piwik2 = Piwik.getTracker("http://URL_2/piwik.php", 4);
piwik2.trackPageView();
} catch( err ) {}
</script>
Note that you can also set the website ID and the piwik tracker URL manually, instead of setting them in the getTracker call:
// we replace Piwik.getTracker("http://example.com/piwik/", 12)
var piwikTracker = Piwik.getTracker();
piwikTracker.setSiteId( 12 );
piwikTracker.setTrackerUrl( "http://example.com/piwik/" );
piwikTracker.trackPageView();
Unit tests covering piwik.js
The Piwik Javascript Tracking API is covered by an extensive Javascript unit test suite to ensure that the code quality is as high as possible, and that we never break this functionnality. Tests are written using QUnit - jQuery unit testrunner. To run the tests, simply checkout the Piwik SVN trunk and go to /path/to/piwik/tests/javascript/. Tests are ran inside your browser.
The Piwik Javascript API has been tested with numerous web browsers, including (but not limited to): Firefox 2, 3.0, 3.1 ; Internet Explorer 5.5, 6, 7, 8 ; Opera 7.54, 8.54, 9.64, 10 ; Safari 3.0, 3.2, 4.0 ; Konqueror 3.5 ; SeaMonkey 1.1, 2.0. We sometimes used browsershots.org to help with tests.
piwik.js is minified
The piwik.js is minified to minimize the size that your website visitors will have to download. We use YUI Compressor to minify the Javascript (more information). You can find the original non minified version in /js/piwik.js.
List of all methods available in the Tracking API
Requesting the Tracker instance from the Piwik class
- Piwik.getTracker( trackerUrl, siteId ) - get a new instance of the Tracker
- [Google Analytics equivalent] _getTracker(account)
- [Yahoo! Analytics equivalent] getTracker(account)
Using the Tracker Object
- enableLinkTracking() - Install link tracking on all applicable link elements
- addListener( element )- Add click listener to a specific link element. When clicked, Piwik will log the click automatically.
- trackGoal( idGoal, [customRevenue], [customVars]); - Manually log a conversion for the goal idGoal, passing in the custom revenue customRevenue if specified, and custom variables (in JSON format) if specified.
- trackLink( url, linkType, customData )- Manually log a click from your own code. url is the URL clicked. linkType can either be 'link' for an outlink or 'download' for a download.
- trackPageView() - Log visit to this page
- [Google Analytics equivalent] _trackPageview(opt_pageURL)
- [Yahoo! Analytics equivalent] submit()
Configuration of the Tracker Object
- setDocumentTitle( string ) - Override document.title
- [Yahoo! Analytics equivalent] YWATracker.setDocumentName("xxx")
- setDomains( array) - Set array of hostnames or domains to be treated as local
- [Google Analytics equivalent] _setDomainName(".example.com")
- [Yahoo! Analytics equivalent] setDomains("*.abc.net")
- setCustomData( object|string ) - Pass custom data to the server
- setSiteId( integer ) - Specify the website ID. Redundant: can be specified in getTracker() constructor.
- setTrackerUrl( string ) - Specify the Piwik server URL. Redundant: can be specified in getTracker() constructor.
- setDownloadClasses( string | array ) - Set classes to be treated as downloads (in addition to piwik_download)
- setDownloadExtensions( string ) - Set list of file extensions to be recognized as downloads. Example: 'doc|pdf|txt'
- addDownloadExtensions( string ) - Specify additional file extensions to be recognized as downloads. Example: 'doc|pdf|txt'
- setIgnoreClasses( string | array ) - Set classes to be ignored if
present in link (in addition to piwik_ignore) - setLinkClasses( string | array ) - Set classes to be treated as
outlinks (in addition to piwik_link) - setLinkTrackingTimer( integer ) - Set delay for link tracking in milliseconds.
Questions?
If you have any question about Javascript Tracking in Piwik, please search on the website, or ask in the forums. Enjoy!
See also
- Does Piwik track visitors without Javascript?
- How does Piwik track downloads?
- How to track error pages (404 pages) in Piwik? Which URLs are 404 and which referers lead to these pages?
- How can I set custom groups of pages (structure) so that page view are aggregated by categories?
- Is the Piwik Javascript Tracking Code XHTML 1.0 compatible?
- Piwik shows "No Data" in all reports.
- Visits from search engines or campaigns are not recorded, Piwik shows "No data available".
- Statistics from Piwik and my other web analytics tool (log analyzer or javascript based) are different, why?
- The Piwik Javascript code shows a red cross (on IE) or a broken image icon instead of the 1*1 transparent Pixel, what is the issue?