Hello,
I found Piwik a while ago and found it very useful. One thing I missed, was the ability to implement the code via an ajax request. So I tried to do it
I started with this new tracking code: (GA inspired)
var _piw = [1,['trackPageView']];
(function(d,t){
var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.async=true;
g.src='//www.example.com/piwik/piwik.js';
s.parentNode.insertBefore(g,s);})(document,'script');
</script>
<noscript>
<p><img src=“http://www.example.com/piwik/piwik.php?idsite=1” style=“border:0” alt="" /></p>
</noscript>
Ok, let me explain:
var _piw = [1,['trackPageView']];
this will be used later in the piwik.js. The ‘1’ (_piw[0]) represents the siteID and _piw[1] is an array with all functions from the JS API which where called, wenn the piwik.js is loaded.
So it’s possible to add more functions and arguments like this:
var _piw = [1,['trackPageView'],['enableLinkTracking'],['setLinkTrackingTimer',250]];
as you can see, the ‘setLinkTrackingTimer’ gets an argument (250)
(function(d,t){
var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.async=true;
g.src='//www.example.com/piwik/piwik.js';
s.parentNode.insertBefore(g,s);})(document,'script');
this is a function which creats a script element add the src attribute to the piwik.js and attach it to the DOM (GA’s async code do nearly the same)
Now I did some changes in the piwik.js:
First i add a global variable PiwikTracker on Line 28:
var PiwikTracker, Piwik, piwik_log, piwik_track;
on line 125 in the ‘loadHandler’ method I added this:
//if _piw is set
if(_piw){
//get new Tracker instance an get the first argument of _piw (which is the siteID)
piwikTracker = Piwik.getTracker(documentAlias.location.protocol+"//www.example.com/piwik/piwik.php",_piw.shift());
//for each argument
for(var i=0;i<_piw.length;i++){
//call it as a function and add arguments
piwikTracker[_piw[i][0]](_piw[i][1],_piw[i][2],_piw[i][3]);
}
}
no the method looks like this:
function loadHandler(loadEvent /* unused */){
if (!hasLoaded){
if(_piw){
piwikTracker = Piwik.getTracker(documentAlias.location.protocol+"//www.example.com/piwik/piwik.php",_piw.shift());
for(var i=0;i<_piw.length;i++){
piwikTracker[_piw[i][0]](_piw[i][1],_piw[i][2],_piw[i][3]);
}
}
hasLoaded = true;
executePluginMethod('load');
for (var i = 0; i < registeredOnLoadHandlers.length; i++) {
registeredOnLoadHandlers[i]();
}
}
return true;
}
This works for me as expected, but is still beta.
I hope someone can improve my code especially the part when calling the tracker functions.
Thats all for now
Xaver