Cookie banners are used to obtain consent for the use of cookies from your website visitors. This is a legal requirement in many countries, including the European Union and its member states - including Germany - as well as other countries around the world.

They help protect user privacy and give them control over how their information is collected and used by your site.

In this post, I want to give you a tool that I used to create the cookie banner for my blog: Cookieconsent.

What are cookies

Cookies are small pieces of data that are stored on a user’s device when they visit a website. These cookies can be used to track user behavior as they navigate the website. They can also be used to store information that the user enters on the website, such as credentials or settings.

Web beacons and similar tracking methods also require explicit consent unless they are absolutely necessary for the operation of the website.

Once you use cookies or web beacons for tracking on your website, you may only do so after the visitor has consented. In addition, there are also some external services that also track your visitors, even if you don’t want them to…

Of course, these services may also only be integrated after clarification and approval. Here are a few examples of services that you may only activate after approval:

  • Google Analytics
  • Google AdSense
  • Google Fonts
  • embedded YouTube video
  • embedded twitch stream
  • embedded image from Imgur
  • Facebook like button

and many more… Especially with non-European services you have to be careful and read their data protection declaration before you integrate them.

At the moment You don’t need cookie consent for personal websites. But keep in mind that blogs with ads or affiliate links are a business and not personal.

In Germany, the requirements for cookie banners are regulated in the Telemedia Act (TMG) and in the Federal Data Protection Act (BDSG). I’m not a lawyer, but broadly speaking, these laws require websites to inform users about the use of cookies and to obtain their consent to that use.

The banner must…

  • be clearly visible and easy to understand: The banner should be prominently displayed on the website and use language that is easy to understand even for users who are not familiar with technical terms.

  • Inform about the use of cookies: The banner should explain what cookies are and how they are used on the website. It should also inform users about the types of cookies that are used, e.g. B. whether they are used for tracking or to store user preferences.

  • obtain user consent: The banner should prompt the user to consent to the use of cookies on the site. This consent should be obtained through an active action, such as B. clicking a button or ticking a box.

  • contain a link to the site’s privacy policy: The banner should contain a link to the site’s privacy policy, which should provide more detailed information about the site’s use of cookies and other data collection practices.

You should note that German law requires websites to give users the option to opt out of the use of cookies used for tracking purposes. This should be made clear in the cookie banner and privacy policy. The best thing you can do is speak to your attorney about it all.

How to use the cookieconsent framework

There are several frameworks that you can use to implement such a banner. Not all of these comply with the above guidelines.

I use cookieconsent from the GitHub user orestbida. Its available under the MIT license. That means you can use it for both personal and commercial purposes.

Before you can include it, you need to make the following three files accessible as static files. It is best to copy them together into a cookieconsent folder.

  • cookieconsent.js
  • cookieconsent.css
  • cookieconsent-init.js

File cookieconsent.js

This is the framework itself.

You should not include this file directly from GitHub! For one, you don’t know if it will be deleted one day. On the other hand, you give the IP address of your website visitors to GitHub before they have the opportunity to file an objection.

download

File cookieconsent.css

This is the file where you can change the design and colors to fit the banner to your website. If you don’t want to change anything, the original colors look very chic. Both light color scheme and dark mode are already included.

download

cookieconsent-init.js file

The init file is where you will need to make most of the changes. This is where the full text and settings of your special cookie banner come in. In this post I only go into the necessary settings. You can find more information on GitHub.

This file consists of at least the initCookieConsent() and the run() command.

As an example, here is my current cookieconsent-init.js file with comments.

// obtain plugin
const cc = initCookieConsent();

// the papermod theme uses "dark" to determin dark mode while 
// cookieconsent uses c_darkmode so we sync it:
var bodyclasses = document.body.classList
if (bodyclasses.contains("dark")) {
  bodyclasses.add('c_darkmode');
}
else {
  bodyclasses.remove('c_darkmode');
}

// run plugin with your configuration
cc.run({
  current_lang: 'en',
  autoclear_cookies: true, // default: false
  page_scripts: true, // default: false

  // mode: 'opt-in'                          // default: 'opt-in'; value: 'opt-in' or 'opt-out'
  // delay: 0,                               // default: 0
  // auto_language: null                     // default: null; could also be 'browser' or 'document'
  // autorun: true,                          // default: true
  force_consent: true, // default: false
  // hide_from_bots: false,                  // default: false
  // remove_cookie_tables: false             // default: false
  // cookie_name: 'cc_cookie',               // default: 'cc_cookie'
  // cookie_expiration: 182,                 // default: 182 (days)
  // cookie_necessary_only_expiration: 182   // default: disabled
  // cookie_domain: location.hostname,       // default: current domain
  // cookie_path: '/',                       // default: root
  // cookie_same_site: 'Lax',                // default: 'Lax'
  // use_rfc_cookie: false,                  // default: false
  // revision: 0,                            // default: 0

  onFirstAction(user_preferences, cookie) {
    // callback triggered only once
  },

  onAccept(cookie) {
    // ...
  },

  onChange(cookie, changed_preferences) {
    location.reload();
  },

  gui_options: {
    consent_modal: {
      layout: 'cloud', // box/cloud/bar
      position: 'top center', // bottom/middle/top + left/right/center
      transition: 'slide', // zoom/slide
      swap_buttons: true, // enable to invert buttons
    },
    settings_modal: {
      layout: 'box', // box/bar
      position: 'left', // left/right
      transition: 'zoom', // zoom/slide
    },
  },

  languages: {
    en: {
      consent_modal: {
        title: 'We use cookies! <img src="/cookieconsent/cookies.webp"></img>',
        description: 'Hi, this website uses essential cookies to ensure its proper operation and tracking cookies and comparable technologies like web beacons to understand how you interact with this website and to provide you with targeted ads. The latter will be set only after consent.  <br><button type="button" data-cc="c-settings" class="cc-link">Let me choose</button>',
        primary_btn: {
          text: 'Accept all',
          role: 'accept_all', // 'accept_selected' or 'accept_all'
        },
        secondary_btn: {
          text: 'Reject all',
          role: 'accept_necessary', // 'settings' or 'accept_necessary'
        },
      },
      settings_modal: {
        title: 'Cookie preferences',
        save_settings_btn: 'Save settings',
        accept_all_btn: 'Accept all',
        reject_all_btn: 'Reject all',
        close_btn_label: 'Close',
        cookie_table_headers: [
          { col1: 'Name' },
          { col2: 'Domain' },
          { col3: 'Expiration' },
          { col4: 'Description' },
        ],
        blocks: [
          {
            title: 'Cookie usage 📢',
            description: 'We use cookies and comparable technologies like web-beacons to ensure the basic functionalities of the website and to enhance your online experience. You can choose for each category to opt-in/out whenever you want. For more details related to cookies and other sensitive data, please read the full <a href="/privacy" class="cc-link">privacy policy</a>.',
          }, {
            title: 'Strictly necessary cookies',
            description: 'These cookies are essential for the proper functioning of my website. Without these cookies, the website would not work properly',
            toggle: {
              value: 'necessary',
              enabled: true,
              readonly: true, // cookie categories with readonly=true are all treated as "necessary cookies"
            },
            cookie_table: [ // list of all expected cookies
              {
                col1: 'cc_cookie', // match all cookies starting with "_ga"
                col2: 'batchest.com',
                col3: '6 months',
                col4: 'Stores your answers to this cookie consent tool.',
              },
            ],
          }, {
            title: 'Advertisement and Targeting cookies and web beacons',
            description: 'These cookies collect information about how you use the website, which pages you visited and which links you clicked on. ',
            toggle: {
              value: 'ads',
              enabled: false,
              readonly: false,
            },
          },
          {
            title: 'Performance and Analytics cookies and web beacons',
            description: 'These cookies and web beacons can collect information about you (IP Address, Browser information etc.) or about which pages you visited and which links you clicked.',
            toggle: {
              value: 'analytics', // your cookie category
              enabled: false,
              readonly: false,
            },
          },
          {
            title: 'External resources',
            description: 'This website does not use external resources that might misuse your data. However if you don\'t want us to load external resources under any circumstances, feel free to disable this checkbox. This might impact your experience on this website as it will disable serval things such as images (like Imgur), videos (like YouTube) or embedded streams (like Twitch).',
            toggle: {
              value: 'analytics', // your cookie category
              enabled: false,
              readonly: false,
            },
          },
          {
            title: 'More information',
            description: 'For any queries in relation to our policy on cookies and your choices, please <a class="cc-link" href="/">contact us</a>.',
          },
        ],
      },
    },
  },
});

It is also best to store this file together with the other two so that you can integrate it into your website.

Include cookieconsent files

Once you have gone through all the settings and have the three files ready, you can integrate them into your <body> or <head> tag in the HTML code of your website. Preferably before you integrate other scripts.

<body>
<link rel="stylesheet" href="/cookieconsent/cookieconsent.css" media="print" onload="this.media='all'">
<script defer src="/cookieconsent/cookieconsent.js"></script>
<script defer src="/cookieconsent/cookieconsent-init.js"></script>

...
</body>

Now the banner should appear when you refresh the webpage.

Script execution only after approval

The aim of the exercise is that the scripts are only executed if the user has given his consent.

In order to have cookieconsent scripts started as soon as the user has consented to a certain cookie category, you must provide them with two special tags:

  • type
  • data-cookiecategory

type="text/plain" prevents the initial execution when the page is loaded. Through data-cookiecategory cookieconsent learns that it should manage this script and which category it should use.

Example Google Analytics

This is how you could run the Google Analytics script only after agreeing to the “analytics” cookie category:

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-123456789-0" type="text/plain" data-cookiecategory="analytics"></script>
<script type="text/plain" data-cookiecategory="analytics">
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-123456789-0');
</script>

Example Google Adsense

This is how you could run the Google Adsense script only after agreeing to the “ads” cookie category:

<script async type="text/plain" data-cookiecategory="ads"
    src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1234567891234567"
    crossorigin="anonymous"></script>

You should give your visitors the option to change their consent afterwards. For example, some users flatly refuse everything. Later they might notice that they have to do without integrated external content such as a Twitch stream.

You can implement a link to call up the cookie settings menu as follows:

<a href="#" style="color:silver" data-cc="c-settings">Cookie Settings</a>

Of course, this link only works after the cookieconsent-init.js script is loaded. I have integrated such a button into the footer of the website.


Could I help? Buy me a drink ! 💙