Mirosław Pragłowski bio photo

Mirosław Pragłowski

.NET/Ruby/... dev

Email Twitter Facebook LinkedIn Instagram Github Stackoverflow Pinterest Foursquare

Cookies, cookies, cookies… all pages are spamming us recently with warnings. Warnings that say nothing to a typical user, warnings that nobody cares for, warnings that irritate most of us.

Of course I could be wrong. All those warnings could be very useful and important to some internet users (not geeks that know how to protect their privacy) and EU bureaucracy is right in their fight to protect poor users who don’t care ;)

Dura lex sed lex

I use cookies. Just typical Google Analytics cookies to get some feedback to know if someone really reads this. So I’m forced to obey the law (BTW users should be warned not only about cookies but about everything stored in local storage). That is why when you enter here for the first time you will be shown a warning banner.

How it works

It is very simple ;) I’ve used 2 great JavaScript libraries: jquery-toastmessage-plugin & jquery.cookie.

Reading & writing cookies

With jquery.cookie it is dead simple. Just add script to your page:

<script src="/path/to/jquery.cookie.js"></script>`

And then to read a cookie use this code:

var value = $.cookie('cookieName');`

All you need to do is check if value is defined and if not show cookie warning message. Then when user accepts your cookies just write a cookie marking his agreement. BTW try to estimate how many new cookies pages you’ve visited recently added to your system :)

Writing a cookie:

$.cookie('cookieName', 'Here will be dragons!', { expires: 365, path: '/' });`

For more details see jquery.cookie GitHub page.

There are a lot of popup boxes, warning panels etc. I used a jquery-toastmessage-plugin because of its simplicity and nice look without need to work on CSS code. Just add:

$().toastmessage('showToast', {
          text     : 'Some text here',
          sticky   : false,
          stayTime : 30000,   
          position : 'top-right',
          type     : 'notice',
          close  : function () {
            // … Just do it!
            console.log("toast is closed ...");
          }
};

See jquery-toastmessage-plugin usage documentation.

Then on close callback write cookie to mark user agreement and it is done… almost because after stayTime (in milliseconds) the toast message is faded out. So I’ve added another callback - called just before close when toast is fading away and not called when user clicked close button. See details in my fork of jquery-toastmessage-plugin.