L
L
loiki2018-04-23 13:44:54
JavaScript
loiki, 2018-04-23 13:44:54

How to find out the client id from google analytics on the first visit of a user?

I need to find out the client id from Google Analytics on the landing page in order to substitute this value in a hidden form field and then transfer it to CRM.
And I ran into an interesting problem. The first time the user logs in, the cookie is not read and the client_id is returned empty.
Google analytics is connected via GTM. I place the script code for reading cookies in the body of the page. I also tried to put it in GTM and run it after the analytics script worked. But it doesn't help much either...
What am I doing wrong? Where did the dog dig?

<script>
  //берем client_id из кукисов аналитики.
 
 
 function Gcid(){
  // функция для получения cookie по имени
  function getCookie(name){
    var matches = document.cookie.match(new RegExp(
      "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ));
    return matches ? decodeURIComponent(matches[1]) : undefined;
  }
     
  
  // исходное значение cookie с именем _ga
  var cidLong = getCookie('_ga');
  // делим на части используя .
  var tmp = cidLong.split('.');
  // берем 3 и 4 фрагмент и склеиваем
  var cid = tmp[2] + '.' + tmp[3];
  // возвращаем значение
  return cid;
}
//конец кода client_id из аналитики
alert (Gcid());
</script>

Maybe you need to put some kind of delay on the reading? Or some other trick to use?
UPD. The code itself is working and reads the client_id. But if you clear the cookies and refresh the page, then nothing is read, although the analyst writes down the client_id already on the first visit.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimonchik, 2018-04-23
@dimonchik2013

And I ran into an interesting problem. The first time the user logs in, the cookie is not read and the client_id is returned empty.

on an empty stomach, only the first pie
, where does the ID come from at the first call?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question