Created
January 24, 2019 15:26
-
-
Save linuskohl/6111438dce408e941b6d0f6118a8778b to your computer and use it in GitHub Desktop.
Insights Cookie Consent Google Analytics Opt-Out Solution
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
var gaProperty = 'UA-XXXXXXXX-X'; | |
// Get the name of the GA tracking disable cookie | |
var disableStr = 'ga-disable-' + gaProperty; | |
// Check if GA cookie exists | |
window[disableStr] = (document.cookie.indexOf(disableStr + '=true') > -1) | |
// Opt-out function | |
function gaOptout() { | |
// Set cookie and global variable | |
document.cookie = disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/'; | |
window[disableStr] = true; | |
} | |
// Opt-in function | |
function gaOptin() { | |
// Expire cookie and set variable to false | |
window[disableStr] = false; | |
document.cookie = disableStr + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; | |
} | |
// Load GA code and send pageview event | |
function track() { | |
if (window[disableStr] === false) { | |
(function(i, s, o, g, r, a, m) { | |
i['GoogleAnalyticsObject'] = r; | |
i[r] = i[r] || function() { | |
(i[r].q = i[r].q || []).push(arguments) | |
}, i[r].l = 1 * new Date(); | |
a = s.createElement(o), m = s.getElementsByTagName(o)[0]; | |
a.async = 1; | |
a.src = g; | |
m.parentNode.insertBefore(a, m) | |
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); | |
ga('create', gaProperty, 'auto'); | |
ga('set', 'anonymizeIp', true); | |
ga('send', 'pageview'); | |
} | |
} | |
track(); | |
// Init cookieconsent | |
$(document).ready(function() { | |
'use strict'; | |
window.cookieconsent.initialise({ | |
"palette": { | |
"popup": { | |
"background": "#ffffff" | |
}, | |
"button": { | |
"background": "#ffea00" | |
} | |
}, | |
"theme": "edgeless", | |
"position": "bottom-right", | |
"type": "opt-out", | |
onInitialise: function(status) { | |
var type = this.options.type; | |
var didConsent = this.hasConsented(); | |
if (type == 'opt-out' && !didConsent) { | |
if (this.options.revokable) { | |
setTimeout(function() { | |
document.getElementsByClassName("cc-revoke")[0].style.display = "block"; | |
}); | |
} | |
} | |
}, | |
// Callback if user selects option | |
onStatusChange: function(status, chosenBefore) { | |
var type = this.options.type; | |
var didConsent = this.hasConsented(); | |
var opted_out = window[disableStr]; | |
if (type == 'opt-out' && !didConsent && !opted_out) { | |
gaOptout(); | |
} | |
if (type == 'opt-out' && didConsent && opted_out) { | |
gaOptin(); | |
} | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment