A simple way to show the 'cookie' warning
The European Union, apparently, has a cookie law. This "requires websites to get consent from visitors to store or retrieve" cookies.
There are some tools out there that allow you to add this message, but it's really simple to do this yourself with a little bit of Javascript.
The first thing to do is to add a <div> to your template's <body>
Let's stop our cookies from travelling. Encapsulate the cookie code in a function:
Now, we have to create a function to show the cookie warning.
Lastly, we have to call the show_cookie_warning() function. Add the function call after our <div>:
And Bob's your uncle.
There are some tools out there that allow you to add this message, but it's really simple to do this yourself with a little bit of Javascript.
The first thing to do is to add a <div> to your template's <body>
Next, we add a new rule to our .css file<div id="cookie_warning"> We use third party "cookies" for ... <input type="button" value="Accept" onclick="javascript:cookies(true);" /> <input type="button" value="Deny" onclick="javascript:cookies(false);" /> </div>
We don't want to show this warning when people have Javascript deactivated.#cookie_warning{display:none}
Let's stop our cookies from travelling. Encapsulate the cookie code in a function:
This prevents the automatic execution of this code.function google_analytics() { (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','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-75171925-1', 'auto'); ga('send', 'pageview'); }
Now, we have to create a function to show the cookie warning.
function show_cookie_warning() { if("undefined" == typeof(Storage)) return; // If localStorage has information, get cookieif(localStorage.length) { var cookie = localStorage.getItem("cookie"); if(!cookie || cookie === "false") return;
If local storage is not available, let's not pester our users with incessant messages. The downside is that our tracking cookies will not travel either.google_analytics(); return; } var msg = document.getElementById("cookie_warning"); msg.style.display = 'block'; }
Lastly, we have to call the show_cookie_warning() function. Add the function call after our <div>:
The cookies() function we've put in the <div> is also really simple:<div id="cookie_warning"></div><script> show_cookie_warning(); </script>
function cookies(b) { var msg = document.getElementById("cookie_warning"); msg.style.display = 'none'; if("undefined" == typeof(Storage)) return; localStorage.setItem("cookie", b); if(b) google_analytics(); }
And Bob's your uncle.
Comments
Post a Comment