Skip to content

Instantly share code, notes, and snippets.

@webdados
Last active February 23, 2024 08:45
Show Gist options
  • Save webdados/ffad958d53af0371e8c36a0fc3ede1ea to your computer and use it in GitHub Desktop.
Save webdados/ffad958d53af0371e8c36a0fc3ede1ea to your computer and use it in GitHub Desktop.
Google Analytics with TCF v2.0 support
/* Need help? Hire us: https://www.webdados.pt/contactos/ */
//We need to wait for the page to be ready, or else the Consent platform may not be loaded yet, and we'll fire the pageview earlier than we should
window.onload = function() {
var google_analytics_id = 'UA-111111-01'; //Replace with yours
//Prepare the data layer
window.dataLayer = window.dataLayer || []
//gtag function
function gtag() {
dataLayer.push(arguments);
}
//Do we have a consent platform installed? If yes, we set the consent to false on the data layer, and wait to get it
//If we don't have a consent plugin, the consent is already "granted" by default on Google Analytics, so everything will work as usual
if ( typeof __tcfapi === "function" ) {
//Set consent to "denied" and wait for the data layer signals
gtag('consent', 'default', {
//ad_storage: 'denied', //This is for ads, not Analytics
analytics_storage: 'denied',
});
//Listen to the consent plugin signals
__tcfapi('addEventListener', 2, function (tcData, success) {
//8 is the consent for Analytics (we need to double-check this, and for other implementations, like ads, or facebook pixels, we need to find out the correct index)
// https://support.didomi.io/iab-tcf-v2-new-purposes/features-summary
if ( success && typeof tcData.purpose.consents[8] != "undefined" && tcData.purpose.consents[8] ) {
//Set consent to "granted", Google Analytics will set the page view a few seconds after
gtag('consent', 'update', {
//ad_storage: 'granted', //This is for ads, not Analytics
analytics_storage: 'granted',
});
}
});
}
//The regular GA code
var gaScript = document.createElement( 'script' );
gaScript.type = 'text/javascript';
gaScript.setAttribute( 'async', 'true' );
gaScript.setAttribute( 'src', 'https://www.googletagmanager.com/gtag/js?id='+google_analytics_id );
document.body.appendChild( gaScript );
gaScript.addEventListener( 'load', function() {
window.dataLayer = window.dataLayer || [];
function gtag(){
dataLayer.push( arguments );
}
gtag( 'js', new Date() );
gtag( 'config', google_analytics_id );
}, false );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment