Is there a way to send Google analytics client_id to Piwik by using javascript solution? Actually I can grab google's client id with the following code snippet as described in the official documentation:
ga(function(tracker) {
var clientId = tracker.get('clientId');
});
I believe the problem would be that Google's ga.js and Piwik's tracking code are running asynchronously and I'm not able to send the client_id to Piwik. I created a custom diemnsion in Piwik and added the relevant code to my tracking script but Piwik says that 'Value is not defined'. I tried to send static ids (e.g. test123) and it's working fine.
I tried to load Piwik's tracking code after page loaded with window.onload
function but it didn't work. I also tried to wait until clientId
variable is generated but it didn't work neither. I tried to turn of the async option for both the tracking scripts with no luck.
I run chrome's timeline debug to see when each tracking codes were loading but even if Piwik's js code loaded later the client_id was not passed to my server.
Any idea how can I send this information to my own server to process it in Piwik? If someone can mention another debug possibility which can help me to identify the issue that would be also great.
As mentioned by EikePierstorff a better solution would be to read up Google's client_id
from the stored cookie. You can get the content of the Google Analytics cookie by issuing the following:
document.cookie.valueOf('_ga')
It lists the content of the cookie. Each element in the cookie is separated by a semicolon (;
). I used the following code to read up the client_id
:
function getClientId(){
var cookie_val_array = document.cookie.valueOf('_ga').split(';');
for (i=0; i < cookie_val_array.length; i++){
if(cookie_val_array[i].indexOf('_ga=') >= 0){
client_id = cookie_val_array[i].split('.')[2] + '.' + cookie_val_array[i].split('.')[3];
}
}
return client_id;
}
And I used the following code to pass it to Piwik:
_paq.push(['setCustomDimension', customDimensionId = 1, customDimensionValue = getClientId()]);
Note: You should have a custom dimension creted in Piwik and your custom dimension may have a different id.
Few things that I would like to highlight:
If this is the first time you run Google Analytics' code snippet on your page and the cookie is not generated yet this code will give an error. So you need to handle that if you want.
Google may change the format and content of its cookie, so please check the content of the cookie before you start to read up any of its values.