Last Updated: February 25, 2016
·
1.667K
· preslavrachev

Using Piwik's JavaScript tracking API to get information about the current visitor in the browser

Piwik is a great OSS analytics solution that is way more powerful, than, I assume most users are aware of. I found its documentation to be rather verbose (never a good sign), to the point that one gets lost in it. One particular example is the JavaScript tracking API.

So, I had the following problem: I wanted a very simple way to obtain some basic information about the current visitor in the browser - is it a first visit, overall number of visits, time of the last visit, etc. This makes a lot of sense for dispalying particular messages for new users, frequent ones, ones who have not used the system for quite a while etc. I did not want to do the tracking in the backend myself, and I also did not want to try to hack the Piwik cookie to scrape the data.

Turns out that Piwik’s JavaScript API can do the job just as well. Yet, I had to figure that out the hard way - with trial and error.

All you need to do is run the following two lines of JavaScript before you apply your visitor-related logic:

var visitorInfo;
_paq.push([ function() { visitor_id = this.getVisitorInfo(); }]);

visitorInfo is a kind of a cryptic-looking array of numbers, but thankfully, I found out what each of those numbers stands for:

visitorInfo[0] = is it a new visitor? (between 0/1)

visitorInfo[1] = the unique Piwik ID of the current visitor

visitorInfo[2] = creation timestamp (a UNIX timestamp in seconds)

visitorInfo[3] = overall number of visits

visitorInfo[4] = current visit timestamp

visitorInfo[5] = last visit timestamp

visitorInfo[6] = last ecommerce order timestamp.

Now, these are not much at all, but enough for a start. Knowing them, one can set a few heuristic rules like the ones I tried to set up.

I am still on my lookout for a more generic solution.

UPDATE: There is an even simpler way to get the visitor info:

javascript var visitorInfo = Piwik.getAsyncTracker();`