Search code examples
google-analyticsgoogle-tag-manager

Custom event tracking in GA4 without cookies


I have developed a system that allows users to create their own widgets and place embed them on their own websites. I am now trying to add custom GA4 event tracking into these widgets so I can see how they get used. I am not interested in any user-specific data so I want to disable GA cookies completely. The other factor to consider is that the website on which the widget is embedded will also likely have their own GA code, so that should remain unaffected.

Here's what I have so far...

var myGACode = 'XYZ';

// initialize gtag if the host site does not already have it
if ( typeof gtag == 'undefined' ) {
    window.dataLayer = window.dataLayer || [];
    window.gtag = function(){dataLayer.push(arguments);}
}

// disable all consent
gtag( 'consent', myGACode, {
    ad_storage: 'denied',
    analytics_storage: 'denied',
    functionality_storage: 'denied',
    personalization_storage: 'denied',
    security_storage: 'denied'
} );
​
// append the gtm tag to the document ​​<head>
var scriptTag = document.createElement('script');
scriptTag.setAttribute( 'src', 'https://www.googletagmanager.com/gtag/js?id=' + myGACode );
scriptTag.setAttribute( 'async', 'async' );
document.getElementsByTagName('head')[0].appendChild( scriptTag );
gtag( 'js', new Date() );
gtag( 'config', myGACode );

The issue I am facing is that the gtag( 'js', new Date() ); line always seems to create a cookie, regardless. If I remove that line, no cookies are created but also no events are received in GA.

Am I attempting the impossible or am I doing it wrong? Any help is appreciated. TIA!


Solution

  • That cookie is for client_id and make GA identify it's the same browser on the website.

    If you really don't want it. You might need to consider measurement protocol and you can create random client_id with your hit.

    The downside is : You will lost the visibility when the user doing on another page or they refresh the website if you set another client_id on next page.

    Ref: Google document about Measurement Protocol