Use only JavaScript for your cookie notice

If you have a website, you probably have a cookie notice installed on it to show your visitors that your site is using cookies or even to request their permission to use those cookies.

If so, it is also very probable that you are using a Framework or CMS (like WordPress) to run your site and even some cache system. Those cache systems may cause conflicts with your cookie notice, especially if they are generating static HTML sites of your content, since the functions used to check if the use of cookies has been accepted may not execute.

For instance, if you use any PHP Framework or CMS which checks via PHP if cookies have been set, this check won’t work at all since it won’t be even executed… This happens very often in most of the WordPress installations I see: the cookie notice is not shown at all or being always showed even when the user already accepted the cookies and all because of the caching plugins.

What can you do to assure that your cookie notice (or any other thing based on cookies or backend functions that should execute in every visit)? Easy: use JavaScript!

Why use JavaScript instead of backend functions?

JavasScript will execute every single time on the browser of the visitor, doesn’t matter if the site being viewed has been cached or not. With JavaScript, you can set up cookies, read them or do almost any other thing nowadays.

If you need something to be executed on the backend that can’t be done directly on JavaScript, you should do one of those things: do not cache this page in concrete or use JavaScript to request any endpoint of your website which is not being cached.

How to check cookies with JavaScript?

If you are using WordPress, you don’t need to code anything; you could use my plugin Easy Cookie Law, which automatically does all the job for you, using JavaScript to check for acceptance and print the cookie notice.

If you are not using WordPress or want to code yourself, managing cookies with JavaScript is very easy:

All cookies are saved on the document object as a string containing a semicolon-separated list of the name of cookies and their value, like this:

cookie-name=value; other-cookie=other-value;

This mean, you only need the name of the cookie that you want to look for and do it like this:

if( document.cookie.indexOf("cookie-name=") >= 0)

Please, note that I have included the symbol “=” there.

After checking if the cookie exists, you may want to get its value:

if (document.cookie.indexOf("cookie-name=")) {
    var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)name-of-the-cookie\s*\=\s*([^;]*).*$)|^.*$/, "$1");
}

After this, you can just an “if” sentence to show or hide your cookie notice or any other thing you want to show/hide.

Read more about the document.cookie object in the MDN Web Docs: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie