Last active
January 13, 2025 10:32
-
-
Save croxton/060899d07a2a9491ab0c20da74fdb700 to your computer and use it in GitHub Desktop.
CookieConsent v3 with Google Tag Manager and Google Consent Mode v2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Somewhere in your main application script... | |
import CookieConsentInit from '../path/to/cookieConsentInit'; | |
new CookieConsentInit(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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