Skip to content

Instantly share code, notes, and snippets.

@danielwagn3r
Created March 14, 2023 16:00
Show Gist options
  • Save danielwagn3r/1c6627f7ec2ba0c229d8b223e60694f0 to your computer and use it in GitHub Desktop.
Save danielwagn3r/1c6627f7ec2ba0c229d8b223e60694f0 to your computer and use it in GitHub Desktop.
Hugo Googly Analytics with cookie consent
<div id="cookie-notice">
<span>We would like to use third party cookies and scripts to improve the
functionality of this website.</span>
<a id="cookie-notice-accept" class="button">Accept</a>
<a id="cookie-notice-deny" class="button">No Thanks</a>
<a href="/privacy">More info</a>
</div>
<script>
function createCookie(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 cookieExists(name) {
return document.cookie.split(';').some((item) => item.trim().startsWith(name)) ? true : false;
}
function readCookie(name) {
if (cookieExists(name)) {
return document.cookie.split('; ').find(row => row.startsWith(name)).split('=')[1];
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
if (readCookie('cookie-notice-option') == 'true') {
{{ if hugo.IsProduction | or (eq .Site.Params.env "production") }}
// Initialize Google Analytics
{{ with .Site.GoogleAnalytics -}}
{{ if hasPrefix . "G-"}}
function loadScriptAsync(scriptSrc, callback) {
if (typeof callback !== 'function') {
throw new Error('Not a valid callback for async script load');
}
var script = document.createElement('script');
script.onload = callback;
script.src = scriptSrc;
document.head.appendChild(script);
}
/* This is the part where you call the above defined function and "calls back"
your code which gets executed after the script has loaded */
loadScriptAsync('https://www.googletagmanager.com/gtag/js?id={{ . }}', function () {
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', '{{ . }}', { 'anonymize_ip': true });
})
{{- end -}}
{{- end }}
{{ end }}
} else if (readCookie('cookie-notice-option') == null) {
document.getElementById('cookie-notice').style.display = 'block';
}
document.getElementById('cookie-notice-accept').addEventListener("click", function () {
createCookie('cookie-notice-option', 'true', 31);
document.getElementById('cookie-notice').style.display = 'none';
location.reload();
});
document.getElementById('cookie-notice-deny').addEventListener("click", function () {
createCookie('cookie-notice-option', 'false', 31);
document.getElementById('cookie-notice').style.display = 'none';
location.reload();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment