×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Javascript
Posted by: Mikael Malmgren
Added: Aug 2, 2018 12:56 PM
Views: 3283
Tags: no tags
  1. function() {
  2.         function GAClientId(clientIdString) {
  3.                 this.parse(clientIdString);
  4.         }
  5.  
  6.         GAClientId.prototype.parse = function(rawString) {
  7.                 var pieces = rawString.split(".");
  8.  
  9.                 this.clientId = pieces.slice(-2).join(".");
  10.                 this.cookieProtocolVersion = pieces[0].replace("GA", "");
  11.                 this.domainDepth = parseInt(pieces[1], 10);
  12.         }
  13.  
  14.         GAClientId.readCookies = function(name) {
  15.                 var nameEQ = name + "=";
  16.                 var ca = document.cookie.split(';');
  17.                 var results = [];
  18.                 for (var i = 0; i < ca.length; i++) {
  19.                         var c = ca[i];
  20.                         while (c.charAt(0) == ' ') {
  21.                                 c = c.substring(1, c.length);
  22.                         }
  23.                         if (c.indexOf(nameEQ) == 0) {
  24.                                 results.push(c.substring(nameEQ.length, c.length));
  25.                         }
  26.                 }
  27.                 return results;
  28.         }
  29.  
  30.         GAClientId.findAll = function() {
  31.                 if (! GAClientId.found) {
  32.                         var clientIds = GAClientId.readCookies("_ga");
  33.                         for (var i = 0; i < clientIds.length; i++) {
  34.                                 clientIds[i] = new GAClientId(clientIds[i])
  35.                         }
  36.  
  37.                         GAClientId.found = clientIds.sort(function(a, b) {
  38.                                 if (a.domainDepth == b.domainDepth)
  39.                                         return 0;
  40.                                 return a.domainDepth > b.domainDepth ? 1 : -1;
  41.                         });
  42.                 }
  43.  
  44.                 return GAClientId.found;
  45.         }
  46.  
  47.         GAClientId.getClientId = function() {
  48.                 var first = GAClientId.findAll()[0];
  49.                 if (!first) {
  50.                         return false;
  51.                 }
  52.                 return first.clientId;
  53.         }
  54.  
  55.         return GAClientId.getClientId();
  56. }