Skip to content

Instantly share code, notes, and snippets.

@croxton
Last active July 23, 2024 15:20
Show Gist options
  • Save croxton/060899d07a2a9491ab0c20da74fdb700 to your computer and use it in GitHub Desktop.
Save croxton/060899d07a2a9491ab0c20da74fdb700 to your computer and use it in GitHub Desktop.
CookieConsent v3 with Google Tag Manager and Google Consent Mode v2
/*
* cookieConsentInit.js
*
* Config and tools for CookieConsent v3, a lightweight, GDPR and CCPA compliant
* Consent Management Tool written in vanilla JS.
* @see https://cookieconsent.orestbida.com/
*/
import * as CookieConsent from "vanilla-cookieconsent";
class CookieConsentInit {
constructor() {
CookieConsent.run({
// Update Google Consent Mode v2
onConsent: () => {
updateGtagConsent();
},
onChange: ({ changedCategories }) => {
updateGtagConsent();
},
categories: {
necessary: {
enabled: true, // this category is enabled by default
readOnly: true // this category cannot be disabled
},
preferences: {
enabled: true,
readOnly: false,
},
statistics: {
enabled: true,
readOnly: false,
// Delete specific cookies when the user opts-out of this category
autoClear: {
cookies: [
{
name: /^_ga/, // regex: match all cookies starting with '_ga'
},
{
name: '_gid', // string: exact cookie name
}
]
}
},
marketing: {
enabled: true,
readOnly: false,
},
},
language: {
default: 'en',
translations: {
en: {
consentModal: {
title: 'Cookies',
description: 'We use cookies to help us improve your site experience. Read more about our <a href="/legal/cookie-policy">Cookies Policy</a>.',
acceptAllBtn: 'Accept all',
acceptNecessaryBtn: 'Reject all',
showPreferencesBtn: 'Manage preferences'
},
preferencesModal: {
title: 'Your cookie preferences',
acceptAllBtn: 'Accept all',
acceptNecessaryBtn: 'Reject all',
savePreferencesBtn: 'Accept current selection',
closeIconLabel: 'Close',
sections: [
{
description: 'Cookies are text files that are placed on your device by web sites that you visit or by clicking on a link to a site within an email. They are used for website functionality as well as to provide information to website owners. For more information, and to change your cookie preferences at any time, please see our <a href="/legal/cookie-policy">Cookies Policy</a>.'
},
{
title: 'Necessary',
description: 'These cookies are essential for the proper functioning and security of the website, and cannot be disabled.',
linkedCategory: 'necessary'
},
{
title: 'Preferences',
description: 'Preference cookies are used to remember user choices that change the way the website looks or behaves.',
linkedCategory: 'preferences'
},
{
title: 'Statistics',
description: 'Statistics cookies help us to understand how visitors interact with our website by collecting and reporting information anonymously.',
linkedCategory: 'statistics'
},
{
title: 'Marketing',
description: 'Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user.',
linkedCategory: 'marketing'
}
]
}
}
}
},
});
function updateGtagConsent() {
if (typeof gtag != "undefined") {
gtag('consent', 'update', {
'ad_storage': CookieConsent.acceptedCategory('marketing') ? 'granted' : 'denied',
'ad_user_data': CookieConsent.acceptedCategory('marketing') ? 'granted' : 'denied',
'ad_personalization': CookieConsent.acceptedCategory('marketing') ? 'granted' : 'denied',
'analytics_storage': CookieConsent.acceptedCategory('statistics') ? 'granted' : 'denied',
'functionality_storage': CookieConsent.acceptedCategory('preferences') ? 'granted' : 'denied',
'personalization_storage': CookieConsent.acceptedCategory('preferences') ? 'granted' : 'denied',
});
}
}
}
}
export default CookieConsentInit;
// Somewhere in your main application script...
import CookieConsentInit from '../path/to/cookieConsentInit';
new CookieConsentInit();
<!DOCTYPE html>
<html>
<head>
<!-- Optionally, set this script to type="text/plain" data-category="statistics"
to stop any pings to Google before user consents -->
<script>
window.dataLayer = window.dataLayer || [];
window.dataLayer.push = function (event) {
// prevent memory leaks in single-page apps
if(event['gtm.element']) {
event['gtm.element'] = event['gtm.element'].cloneNode(true);
}
return Array.prototype.push.apply(this, arguments);
}
function gtag() {
window.dataLayer.push(arguments);
}
// Google Consent Mode v2 default values
gtag("consent", "default", {
ad_personalization: "denied",
ad_storage: "denied",
ad_user_data: "denied",
analytics_storage: "denied",
functionality_storage: "denied",
personalization_storage: "denied",
security_storage: "granted",
wait_for_update: 500,
});
gtag("set", "ads_data_redaction", true);
// Include Google Tag Manager
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','YOUR_TAG_ID');
</script>
<script defer src="/dist/main.js"></script>
</head>
<body>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment