Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract Google Analytics campaign data from their cookie with Javascript?

I'd like to be able to pull out the data stored in the Google Analytics tracking cookie with all the campaign tracking information using Javascript. It needs to work with the newer version of GA using ga.js, not urchin.js. I found a method that works with urchin.js but we don't use that for our tracking. Does anybody know how to extract the Campaign, Source, Medium, Content and Term from the cookie Google uses?

like image 282
Shawn Steward Avatar asked Nov 06 '09 16:11

Shawn Steward


1 Answers

Now works:

   function extractAnalyticsData(){
      var data = {};
      var ga_source = '';
      var ga_campaign = '';
      var ga_medium = '';
      var ga_term = '';
      var ga_content = '';
      var gc = '';
      var c_name = "__utmz";
      if (document.cookie.length>0){
          c_start=document.cookie.indexOf(c_name + "=");
          if (c_start!=-1){
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            gc = unescape(document.cookie.substring(c_start,c_end));
          }
      }
      data.gc = gc;
      if(gc != ""){
          var y = gc.split('|'); 
        for(i=0; i<y.length; i++){
          if(y[i].indexOf('utmcsr=') >= 0) data.ga_source = y[i].substring(y[i].indexOf('=')+1);
          if(y[i].indexOf('utmccn=') >= 0) data.ga_campaign = y[i].substring(y[i].indexOf('=')+1);
          if(y[i].indexOf('utmcmd=') >= 0) data.ga_medium = y[i].substring(y[i].indexOf('=')+1);
              if(y[i].indexOf('utmcct=') >= 0) data.ga_content = y[i].substring(y[i].indexOf('=')+1);
          if(y[i].indexOf('utmctr=') >= 0) data.ga_term = y[i].substring(y[i].indexOf('=')+1);
        }
      }
      return data;
    };
    extractAnalyticsData();
like image 166
mpz Avatar answered Sep 22 '22 06:09

mpz