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>

<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>
 Next, we add a new rule to our .css file

#cookie_warning{display:none}
We don't want to show this warning when people have Javascript deactivated.


Let's stop our cookies from travelling. Encapsulate the cookie code in a function:

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');
}

This prevents the automatic execution of this code.


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 cookie 
    if(localStorage.length)
    {
        var cookie = localStorage.getItem("cookie");
        if(!cookie || cookie === "false")
            return;
        google_analytics();
        return;
    }

    var msg = document.getElementById("cookie_warning");
    msg.style.display = 'block';
}
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.


Lastly, we have to call the show_cookie_warning() function. Add the function call after our <div>:

<div id="cookie_warning">
</div>
<script>
    show_cookie_warning();
</script>
The cookies() function we've put in the <div> is also really simple:
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

Popular posts from this blog

Linear Mortgage Calculation

How I 'hacked' the Google App Engine