How to use visit time and duration for tracking goals in Piwik

I’m (ab)using custom variables and the client-side clock to fire Piwik goals like »Visit has been at least 5 minutes long«. Here’s how:

In the regular Piwik code at the bottom of your html page, just add following code, right before piwikTracker.trackPageView();

var currentTime = new Date();
var mystamp = currentTime.getTime();
var piwikStart;
if (piwikStart = piwikTracker.getCustomVariable(1)) {
if ((mystamp - piwikStart[1]) > 300000 ) { piwikTracker.trackGoal(99); }
} else {
piwikTracker.setCustomVariable( 1, "StartTime", ""+mystamp, "visit");
  • Where 300000 is the amount of milliseconds for this goal, in this case 5 minutes = 300 seconds = 300000 milliseconds
  • Where 99 is the id of your goal, which you have to configure before adding this code. It has to fire »manually«, of course. That’s what we do here.

Please comment below and tell me about bugs and stuff!