Stylish Multilingual GDPR & Cookie Consent Popup In Vanilla JavaScript

Category: Javascript , Recommended | August 7, 2023
Author:orestbida
Views Total:1,249 views
Official Page:Go to website
Last Update:August 7, 2023
License:MIT

Preview:

Stylish Multilingual GDPR & Cookie Consent Popup In Vanilla JavaScript

Description:

A standalone JavaScript library that displays a stylish, multilingual, customizable, accessible, GDPR compliant cookie consent popup to make your site comply with GDPR and EU Cookie Law.

Click the Learn More link to display Cookie Consent Policy content in a popup window.

More Features:

  • Auto language detection.
  • Configurable expiration date.
  • Easy to create your own styles.
  • Cookie settings modal.

How to use it:

1. Insert the JavaScript file cookieconsent.js and stylesheet cookieconsent.css into the HTML document.

<link href="/dist/cookieconsent.css" rel="stylesheet" />
<script src="/dist/cookieconsent.js"></script>

2. Initialize the library and display the cookie consent popup on page load.

var cookieconsent = initCookieConsent();
cookieconsent.run({
  onAccept: function(cookies){        
    if(cc.allowedCategory('analytics_cookies')){
      cc.loadScript('https://www.google-analytics.com/analytics.js', function(){    
        ga('create', 'UA-XXXXXXXX-Y', 'auto');  //replace UA-XXXXXXXX-Y with your tracking code
        ga('send', 'pageview');
      });
    }
  },
});

3. Manage third-party scripts.

cookieconsent.run({
  page_scripts: true,
  // more options here
});
<script type="text/plain" data-cookiecategory="analytics" src="myscript.js" defer></script>

4. Customize the cookie consent popup with the following options.

cookieconsent.run({
  // 'opt-in', 'opt-out'
  mode: 'opt-in',
  // language
  current_lang : "en",
  // auto display on page load
  autorun: true,
  // cookie name
  cookie_name: 'cc_cookie',
  // 6 months
  cookie_expiration : 182,
  // cookie domain
  cookie_domain: location.hostname, 
  // cookie path
  cookie_path: "/",
  // sameSite attribute
  cookie_same_site: "Lax",
  // specify if you want to set a different number of days - before the cookie expires - when the user accepts only the necessary categories
  cookie_necessary_only_expiration: null,
  // enable if you want the value of the cookie to be rfc compliant (it's base64 encoded)
  use_rfc_cookie: false,
  // enable if you don't want the plugin to run when a bot/crawler is detected
  hide_from_bots: false,
  // delay in ms
  delay: 0,
  // path to theme CSS
  theme_css: '',
  // enable if you want to block page navigation until user action
  force_consent: false,
  // enable revisions
  revision: 0,
  // Language auto-detection strategy
  // Null to disable (default), 
  // "browser" to get user's browser language or "document" to read value from <html lang="..."> of current page.
  // If language is not defined => use specified current_lang
  auto_language: null,
  // automatically delete cookies when user opts-out of a specific category inside cookie settings
  autoclear_cookies: false,
  // enable if you want to easily manage existing script tags
  page_scripts: false,
  // remove the html cookie tables
  remove_cookie_tables: false,
  languages: {
    // add your own language here
  },
  gui_options: {
    consent_modal : {
      layout : 'cloud',               // box/cloud/bar
      position : 'bottom center',     // bottom/top + left/right/center
      transition: 'slide'             // zoom/slide
    },
    settings_modal : {
      layout : 'box',                 // box/bar
      // position : 'left',           // left/right
      transition: 'slide'             // zoom/slide
    }
  }
  onAccept: function(){
    // do something
  },
  onChange: function(){
    // do something
  },
  onFirstAction: function(){
    // do something
  },
  
});

5. API methods.

// show the cookie consent popup
cookieconsent.show(delay);
// hide the cookie consent popup
CookieConsent.hide();
// show cookie settings
CookieConsent.showSettings(delay);
// hide cookie settings
cookieconsent.hideSettings();
// allow cookie category
cookieconsent.allowedCategory(category_name);
// update language
cookieconsent.updateLanguage(lang);
// check if a cookie is valid
cookieconsent.validCookie(cookie_name);
// load script
cookieconsent.loadScript(path, callback, customAttributes>);
// Set cookie's "data" field to whatever the value of the `value` prop. is
cookieconsent.set('data', {value: {id: 21, country: "italy"}});
// retrieve all accepted categories (if cookie exists)
cookieconsent.get('level'); 
    
// retrieve custom data (if cookie exists)
cookieconsent.get('data');  
    
// retrieve revision number (if cookie exists)
cookieconsent.get('revision'); 
// get configs
cookieconsent.getConfig('current_lang'); 
// get user preferences
cookieconsent.getUserPreferences()
// Only add/update the specified props.
cookieconsent.set('data', {value: {id: 22, new_prop: 'new prop value'}, mode: 'update'});
// accept categories
cookieconsent.accept(accepted_categories, optional_rejected_categories);
// erase cookies
cookieconsent.eraseCookies(cookie_names, optional_path, optional_domains)

6. Enable a trigger button to toggle the cookie settings modal. Available data-cc actions:

  • c-settings: show settings modal
  • accept-all: accept all categories
  • accept-necessary: accept only categories marked as necessary/readonly (reject all)
  • accept-selection: accept currently selected categories inside the settings modal
<a href="javascript:void(0);" aria-label="View cookie settings" data-cc="c-settings">Cookie Settings</a>

Changelog:

v2.9.2 (08/07/2023)

  • Fix a11y issue caused by missing aria-level attribute
  • Fix .updateScripts() method doesn’t work when mode is set to ‘opt-out’

v2.9.1 (08/07/2023)

  • Fix wrong toggle states after opening and closing the settings modal
  • Code refactoring
  • Update dependencies

v2.9.0 (04/21/2023)

  • Add new CSS variables
  • Allow custom script type via the data-type attribute
  • Add settings_modal.cookie_table_caption option for better a11y
  • Allow custom z-index value via the –cc-z-index css variable
  • Allow data-cc attributes on all HTML elements
  • Disable transitions if prefers-reduced-motion is enabled
  • Discard unsaved settings inside settings_modal
  • Fix focus restoration when modals are hidden
  • Small ui tweaks: slightly reduce padding
  • Remove old IE8 specific css rules
  • Update all dependencies
  • Code refactoring/cleanup

v2.8.9 (11/28/2022)

  • Bugfixes

v2.8.8 (10/18/2022)

  • Remove hardcoded css values for a simpler styling
  • Set z-index to highest possible value
  • Added css variable to configure border radius
  • Bugfix

v2.8.6 (09/03/2022)

  • Bugfix: cookie not deleted if not .domain.com
  • Restore level property to avoid breaking change in patch version

v2.8.5 (08/02/2022)

  • Bugfix

v2.8.4 (07/27/2022)

  • Fix incompatible/missing types

v2.8.3 (07/23/2022)

  • Fixed a UI bug
  • Added build tools (postcss && terser)
  • Minor UI tweak: modals have a slightly reduced padding

v2.8.2 (07/02/2022)

  • Set up automatic NPM releases
  • Fix minified files and hide_from_bots option
  • Fix types

v2.8.1 (06/22/2022)

  • Typescript Support
  • Fix issue with nextjs

v2.8.0 (01/16/2022)

  • Clear unused cookies onFirstAction
  • data-cc attribute now supports: accept-all, accept-necessary and accept-selection values
  • Added new mode option: opt-in/opt-out
  • Added .updateLanguage(<lang>) method
  • Allow .getConfig() to retrieve all config. properties
  • Allow .updateLanguage(<lang>, <force>) to forcefully refresh current modals
  • Minor code refactoring
  • Bugfixes

v2.7.2 (12/23/2021)

  • Fixed cookie_necessary_only_expiration option

v2.7.1 (12/12/2021)

  • Pass cookie data also to onFirstAction callback
  • Fix .getUserPreferences() not working if consent is already given
  • Fix wrong background-color on old browsers that don’t support css variables

v2.7.0 (12/07/2021)

  • Added .updateScripts() method to manage dynamically added scripts
  • Added .getConfig() method to read configuration values
  • Added language autodetection strategy based on <html lang>
  • Added swap_buttons inside gui_options to invert button’s order
  • Added onFirstAction and getUserPreferences() for logging/analytics purposes
  • Added cookie_necessary_only_expiration option
  • Always allow the middle position inside gui_options
  • bugfixes:

v2.6.2 (11/14/2021)

  • Fix eslint warnings/errors
  • Fix a ui bug which caused uneven margins when gui_options was omitted
  • Apply hide_from_bots also to WebDriver

v2.6.1 (10/09/2021)

  • breaking change: if use_rfc_cookie is enabled, encode cookie value using encodeUriComponent instead of btoa (base64)
  • fix accessibility issue

v2.6.0 (10/07/2021)

  • added .set() API
  • added .get() API
  • added option to vertically align the consent modal using the middle keyword
  • added use_rfc_cookie option (encodes the cookie value in base64 format)
  • added hide_from_bots option
  • enable force_consent only if consent modal is visible
  • fix: cookies not getting deleted if remove_cookie_tables option is enabled
  • minor tweaks and code refactoring

v2.5.1 (09/15/2021)

  • fix: revision option not working properly
  • fix: eraseCookies() function not working on localhost

v2.5.0 (08/29/2021)

  • added .accept() method
  • added .eraseCookies() method
  • added support for revisions (when cookieconsent terms change => re-prompt users to accept)
  • use better system fonts
  • minor ui tweaks

v2.4.7 (06/18/2021)

  • minor css bugfix (fixed table headers which sometimes covered table cells)
  • added option to specify custom domain for each cookie inside cookie_table

v2.4.6 (06/02/2021)

  • improved autoclear_cookies function
  • fixed minor ui bug which caused links inside cookie tables to be unclickable

v2.4.5 (05/28/2021)

  • allow html use inside table cells for more flexibility
  • fix firefox bug with cloneNode() on script tags
  • added option to set custom cookie name

v2.4.4 (05/27/2021)

  • fix occasional transition skip
  • manage unhandled error caused by a very specific config. object
  • minor code/css refactoring

v2.4 (05/26/2021)

  • added some basic options for layout and position via gui_options
  • better support for existing <script> tags which can now easily be managed through the cookieconsent
  • added new cookie settings: cookie_path, cookie_same_site
  • added new option to hide the html cookie tables
  • minor css refactoring && IE bugfixes

v2.3 (04/30/2021)

  • support WAI-ARIA
  • added css variables for an easier management of color schemes
  • added possibility to append the generated html to any element (default :=> document.body)
  • improved accessibility via css generated icons

v2.2 (03/23/2021)

  • fixed cookie (cc_cookie) not being set with https enabled on localhost
  • fixed minor bug on IE where .innerHTML throws an exception

v2.1 (03/06/2021)

  • added forced consent (block page navigation until consent is given)
  • autoload_css now uses ajax to ensure the css is properly loaded
  • minor code refactoring and optimizations

02/20/2021

  • minor css refactoring
  • catch css load error without local server

11/26/2020

  • darkmode button minor bugfix

11/14/2020

  • darkmode read-more button hover fix

11/09/2020

  • minor code refactoring

11/08/2020

  • fix minor bugs & replace innerText with innerHTML

11/07/2020

  • minor bugfix, increased z-index to 1000000

v1.2 (11/05/2020)

  • add support for custom expiration date with cc_cookie_expiration
  • add support for auto-removal of unused cookies based on cookiepolicy preferences with cc_autoclear_cookies
  • can now autolad css or not with cc_autoload_css
  • fix minor (bug/incoherence): cookiepolicy did not remember/retrieve saved preferences and always displayed default values

10/24/2020

  • add custom table headers

10/02/2020

  • fix minor ui bugs on ie8

09/29/2020

  • fix minor css bug

09/20/2020

  • remove unused code

09/19/2020

  • improve cookie-policy ui

09/15/2020

  • bug fixed for IE 8/9.

09/08/2020

  • now you can bind any buttons to open the cookie policy

09/08/2020

  • cookie-policy-ui update

09/07/2020

  • fix minor glitch on small screen devices

09/06/2020

  • minor changes

09/04/2020

  • fix double saved cookies

09/01/2020

  • fix minor glitch

You Might Be Interested In:


3 thoughts on “Stylish Multilingual GDPR & Cookie Consent Popup In Vanilla JavaScript

  1. Koky

    Hi! I really like this snippet, but I’m newbie and I have a simple question, which file I need to edit to change the text of popup? Thank you so much.

    Reply
  2. Francisco Tazón Vega

    Hi!
    Thank you for your code, great job!

    Can it be done that the first screen, the one that starts with ‘I use cookies….’ is modal, so I can comply with a Spanish resolution that requires that the request is also modal?

    Thanks in advance

    Reply

Leave a Reply