The aim is simple, run the google tracking code AFTER the user has accepted and if the user do not accept, do not run.
I went with placing the code inside the tag, but I am struggling to understand how to incorporate a "dismiss" option as well.
This is my "work in progress" code as of right now:
<script>
(function() {
if (!localStorage.getItem('cookieconsent')) {
document.body.innerHTML += '\
<div class="cookieconsent" style="position:fixed;padding:20px;left:0;bottom:0;background-color:#000;color:#FFF;text-align:center;width:100%;z-index:99999;">\
This site uses standard cookies and Google Analytics. By clicking on "I understand", you agree to their use. \
<a href="#" style="color:#CCCCCC;font-weight:bold;">I Understand</a>\
</div>\
';
document.querySelector('.cookieconsent a').onclick = function(e) {
e.preventDefault();
document.querySelector('.cookieconsent').style.display = 'none';
localStorage.setItem('cookieconsent', true);
};
}
})();
</script>
And from what I understand, I need to place the google tracking after this line:
localStorage.setItem('cookieconsent', true);
But since the script tag is already opened, how do I do that?
Example of the tracking code:
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXXXXX');
</script>
On top of this, I'm not sure how to add a dismiss option so that the google code does not run. I'm grateful for all the input I can get.
This probably contains the answer to your question Consent Mode (beta):
"Consent Mode (beta) allows you to adjust how your Google tags behave based on the consent status of your users. You can indicate whether consent has been granted for Analytics and Ads cookies. Google's tags will dynamically adapt, only utilizing measurement tools for the specified purposes when consent has been given by the user."