0

I have a question about the possibility of assigning an id to a device (pc, mobile or tablet).

I would like to assign a unique device ID to a single device in order to track its path on my website. My site does not require registration and login so I cannot use the classic UserID.

I should integrate it with a variable on Google Tag Manager and then it should be written in Javascript.

Can anyone help me?

Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449

1 Answers1

0

Even I guess the original GA client id is already what you are chasing for. You can take a look about it first.

But here still have the option to do your own device id:

1. You can create a Tag first in Google Tag Manager

type : Custom JavaScript

Don't add the trigger yet. We will get back to this.

<script>
  (function(){
    function setCookie(name,value,days) {
      var expires = "";
      if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
      }
      document.cookie = name + "=" + (value || "")  + expires + "; path=/";
    }
    function getCookie(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
      }
      return null;
    }
    function eraseCookie(name) {   
      document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }

    // From another stack overflow answer https://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript
function uuidv4() {
  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16));
}

    var deviceIdCookie = getCookie("self_device_id");
    if(!deviceIdCookie){
      var newDeviceId = uuidv4();
      setCookie("self_device_id", newDeviceId, 3650);
    }
  })();

</script>

2. Create a variable to get your device id cookie

enter image description here

3. Create the trigger back to step1's tag

enter image description here

4. Done

Now you have the cookie of your own device-id if the user don't have one. You can use the cookie {{cookie_self_device_id}} in the GA4 configuration as a user property. enter image description here

darrelltw
  • 1,734
  • 1
  • 10
  • 21
  • Thank for you answer Darrellwan.. I have only a problem.. Step1, could you explain me how can I create a tag with custom javascript? – Cesare Spani Aug 02 '22 at 15:49