10th June, 2012

EU Cookie Directive compliance script

In light of the EU Cookie Directive ruling, I have written a small piece of JavaScript to put on any site which uses cookies. The code overlays a once-only message over the site with a configurable link to your cookie information page.

How To Use

  1. Download the code (right click Save As)

  2. Add a link to the JavaScript file in your HTML. I use

    <script type="text/javascript" src="/media/layout/js/cookiePopup.js" ></script>

  3. Add your configuration options using a small piece of script on your pages. I suggest you add it to the bottom of the page, just before the closing tag.

Possible configuration options are:

COOKIE_POPUP_POSITION: 'top'

or

COOKIE_POPUP_POSITION: 'bottom'

Either top or bottom realistically.

You can also override COOKIE_NAME and COOKIE_VALUE which refer to the cookie name and cookie value to stop the message appearing again. In case of cookie clashes.

To block Google Analytics or other trackers from dropping cookies until the user has consented, use the following script:

<script type="text/javascript">

    if (CookiePopupManager.userHasAcceptedCookies()) {

        // Put your Google Analytics or other tracking in hereā€¦

    }

</script>

Code

(In case you can't download it)

/**
 * Copyright (c) 2012 Adam Auckland
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
 * Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

/**
 * @namespace
 */
(
    function() {
        /**
         * @namespace
         * @description A simple cookie message popup to be compliant with the EU cookie directive ruling.
         */

        CookiePopupManager = {

            /**
             * @default
             * @description Store the configuration and allow some defaults which may be overriden
             */

            configuration: {
                COOKIE_INFORMATION_URL: '/',
                COOKIE_POPUP_POSITION: 'top',
                COOKIE_NAME: 'EUCookieAccepted',
                COOKIE_VALUE: 'Cookies Accepted'
            },



            /**
             * @function
             * @description Create a div with a message and attach it to the body element.
             */

            initialise: function (configuration) {
                if (configuration !== undefined) {
                    CookiePopupManager.overrideConfiguration(configuration);
                }

                if (CookiePopupManager.userHasAcceptedCookies() ) {
                    return;
                }

                /**
                 * Create a popup and store a reference to it
                 */

                CookiePopupManager.messageContainer = CookiePopupManager.createPopupMessage();

                if (CookiePopupManager.messageContainer != null) {

                }
            },



            /**
             * @function
             * @description Merge the users configuration into our default configuration
             */

            overrideConfiguration: function(configuration) {
                for(var configurationItemKey in configuration) {
                    CookiePopupManager.configuration[configurationItemKey] = configuration[configurationItemKey];
                }
            },



            /**
             * @function
             * @description CreatePopupMessage
             */

            createPopupMessage: function () {
                var cookieHtmlBuilder = [];
                cookieHtmlBuilder.push( '<div id="cookiePopupContainer" style="position: fixed; ');
                cookieHtmlBuilder.push( CookiePopupManager.configuration.COOKIE_POPUP_POSITION );
                cookieHtmlBuilder.push( ': 0px; background: #fff; border: solid 1px #ccc; padding: 1em; margin: 0; width: auto;">' );
                cookieHtmlBuilder.push( 'This site uses cookies. By using this site you agree to allow cookies to be stored in your browser. ');
                cookieHtmlBuilder.push( 'For more details visit <a href="' + CookiePopupManager.configuration.COOKIE_INFORMATION_URL );
                cookieHtmlBuilder.push( '">the cookie page</a> for details. ' );
                cookieHtmlBuilder.push( '<span style="margin-left: 4em;"><a href="#" onclick="return CookiePopupManager.closePopup();">I agree to accept cookies</a></span></div>' );

                var cookieHtml = cookieHtmlBuilder.join(' ');

                var searchForBody = document.getElementsByTagName('body');
                if(searchForBody.length == 1) {
                    var bodyTag = searchForBody[0];

                    var popupDiv = document.createElement('div');
                    popupDiv.innerHTML = cookieHtml;
                    bodyTag.appendChild(popupDiv);

                    return popupDiv;
                }

                /**
                 * No body element. exit
                 */
                return null;
            },



            /**
             * @function
             * @description Close the cookie popup container.
             */

            closePopup: function () {
                CookiePopupManager.storeCookie();

                var cookiePopupParent = CookiePopupManager.messageContainer.parentNode;
                cookiePopupParent.removeChild(CookiePopupManager.messageContainer);
            },



            /**
             * @function
             * @description Check for a saved cookie indicating the user has accepted cookies
             */

            userHasAcceptedCookies: function() {
                var cookieArray = document.cookie.split(";");
                var cookieName, cookieValue, cookieSplit;

                for (i = 0; i < cookieArray.length;i++) {
                    if (cookieArray[i].indexOf('=') != -1) {
                        cookieSplit = cookieArray[i].split('=');
                        cookieName = cookieSplit[0].replace(/^\s+|\s+$/g, '');
                        cookieValue = unescape(cookieSplit[1].replace(/^\s+|\s+$/g, ''));

                        if ((cookieName == CookiePopupManager.configuration.COOKIE_NAME) &&
                            (cookieValue == CookiePopupManager.configuration.COOKIE_VALUE)) {
                            return true;
                        }
                    }
                }

                return false;
            },



            /**
             * @function
             * @description Store a cookie in the browser
             *
             * Set the cookie to expire ten years in the future.
             * Note - some browsers may potentially have problems with dates
             * greater than 2038, although I would be surprised if this hasn't been fixed.
             *
             * Search for Y2038 issue for more information.
             *
             * Since we are only setting the cookie once, in ten years time the message will reappear.
             * I have decided I would rather that inconvenience than add
             * extra code in to reset the expiry on every page refresh.
             *
             */

            storeCookie: function() {
                var expiryDate = new Date();
                expiryDate.setDate(expiryDate.getDate() + 365 * 10);

                var cookieValue = escape(CookiePopupManager.configuration.COOKIE_VALUE) + '; expires=' + expiryDate.toUTCString() + '; path=/';
                var previousCookies = document.cookie;

                if(previousCookies != '') {
                    previousCookies = ';' + previousCookies;
                }

                /**
                 * Add the cookie in
                 */

                document.cookie = CookiePopupManager.configuration.COOKIE_NAME + "=" + cookieValue + previousCookies;
            }
        }
    }
)();

Caveat: It is too soon to say whether this is fully compliant with the EU directive. My take is that doing something is better than nothing.

License: It's released under a MIT license; you can do whatever you want with it.

 

The opinions expressed here are my own and not those of my employer.