david-novafacile / cookieconsent

:cookie: Simple cross-browser cookie-consent plugin written in vanilla js

Home Page:https://orestbida.com/public/demo-projects/cookieconsent/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cookie Consent

License: MIT Size

Simple cross-browser cookie consent plugin written in plain javascript.

Why though

I wanted a simple, lightweight but also extensible plugin, which could be placed in my own web server without the need of making additional external requests. The reason was to further optimize the loading speed of my website.

Main features

  • Cross-browser support (IE8+)
  • Standalone (no external dependecies needed)
  • Lightweight (~ 10kb for optimized/minified version)
  • Can easily add support for additional languages
  • Automatic browser language detection
  • No additional external http requests

CDN

// dist version (no verbose mode)
https://cdn.jsdelivr.net/gh/orestbida/cookieconsent/dist/cookieconsent.js

// src version (with verbose mode)
https://cdn.jsdelivr.net/gh/orestbida/cookieconsent/src/cookieconsent.js

How to run

  • Include file (or load it dynamically)
    // either locally
    <script src="<your_path>/cookieconsent.js"></script>
    
    // or load it via cdn
    <script src="https://cdn.jsdelivr.net/gh/orestbida/cookieconsent/dist/cookieconsent.js"></script>
  • Obtain Cookie-Consent plugin
    const CookieConsent = initCookieConsent();
  • Initialize cookieconsent (you need to provide a config. object)
    CookieConsent.run(<config_object>);
  • Show cookieconsent modal (will show only if cookieconsent was not alredy accepted)
    CookieConsent.show(<optional_delay_value>);
  • Hide cookieconsent modal
    CookieConsent.hide();
  • Show cookie policy modal
    CookieConsent.show_policy();
  • Hide cookie policy modal
    CookieConsent.hide_policy();

Custom config. settings

All available config settings shown in the example below.

CookieConsent.run({
    
    // if true, shows cookie-consent modal as soon as initialized
    cc_autorun : false, 						
    
    // shows cookie-consent modal after 0 milliseconds 
    cc_delay : 0,	

    // if url is specified, the cookie-consent policy will not be generated
    // and the learn more button will instead be linked to the specified url
    cc_policy_url : null,	

    // if set to true, prints all config/info/error messages on console
    cc_enable_verbose : true,	

    // set default language (from those defined in cc_languages)
    cc_current_lang : 'en',	
    
    // if set to true, sets cookie-consent language to that of the browser in use 
    // (if that language is defined in cc_languages)
    cc_auto_language : true,	
    
    // if set to true, autoloads css based on cc_theme_css path [NEW IN VERSION 1.2]
    cc_autoload_css : true,
    
    // path to cookieconsent.css
    cc_theme_css : '<your_path>/cookieconsent.css',

    // number of DAYS before cc_cookie expires [NEW IN VERSION 1.2]
    cc_cookie_expiration : 182,

    // if true, erase unused cookies (based on selected preferences inside cookiepolicy modal) [NEW IN VERSION 1.2]
    cc_autoclear_cookies: true,
    
    // optional callback function to call when the visitor accepts the cookie consent
    cc_accept_callback : function(cookies){
        // print accepted cookie settings
        console.log('cookie consent is accepted!', cookies);

        if(cookies.level.contains('functionality_cookies')){
            // js code here
        }
    },

    // define your own cookie-consent and cookie-policy
    // it's up to you to make it gdpr compliant
    cc_languages : [
        {
            lang : 'en',
            modal : {
                cc_title :  "I use cookies",
                cc_more_text :  "Learn more", 
                cc_accept_text : "I understand",
                cc_description :  'My website uses essential cookies necessary for its functioning. By continuing browsing, you consent to my use of cookies and other technologies.',
            },
            policy : {
                ccp_title : "Cookie Policy",
                ccp_save_text : "Save preferences",
                // ccb_table_headers is REQUIRED if any ccb_cookies_table is used
                ccb_table_headers : [
                    {col1: "Name" }, 
                    {col2: "Domain" }, 
                    {col3: "Expiration" }, 
                    {col4: "Description" }, 
                    {col5: "Type" }
                ],
                ccp_blocks : [
                    {
                        ccb_title : "What are cookies",
                        ccb_description: 'Cookies are very small text files that are stored on your computer when you visit a website. I use cookies to assure the basic functionalities of the website and to enhance your online experience. I use many different types of cookies which you can check on the sections below.'
                    },{
                        ccb_title : "Strictly necessary cookies",
                        ccb_description: 'These cookies are essential for the proper functioning of my website. Without these cookies, the website would not work properly.',
                        ccb_cookies_table : [
                            {
                                col1: 'cc_cookie',
                                col2: 'orestbida.com',
                                col3: 'After 3 months (Starting from the moment the cookie-consent was accepted)',
                                col4: 'Used to know whether a visitor has accepted the cookie consent or not.',
                                col5: 'Permanent cookie'
                            },
                            {
                                col1: 'cc_level',
                                col2: 'orestbida.com',
                                col3: 'After 3 months (Starting from the moment the cookie-consent was accepted)',
                                col4: 'Used to know the accepted level of cookie consent (E.g.  essential cookie only, full cookie consent ...)',
                                col5: 'Permanent cookie'
                            }
                        ],
                        ccb_switch : {
                            value : 'necessary_cookies',
                            enabled : true,
                            readonly: true
                        }
                    },{
                        ccb_title : "Functionality cookies",
                        ccb_description: 'These cookies are used to provide you with a more personalized experience on my website and to remember choices you make when you browse the website. For example, whether or not you enabled dark-mode on this website.',
                        ccb_switch : {
                            value : 'functionality_cookies',
                            enabled : true,
                            readonly: false
                        },
                        ccb_cookies_table: [
                            {
                                col1: 'darkmode',
                                col2: 'orestbida.com',
                                col3: 'One week after the cookie has been created',
                                col4: 'Used to remember visitor preferences. If darkmode was enabled, then the next time you visit the website, darkmode will be automatically turned on.' ,
                                col5: 'Permanent cookie'
                            }
                        ]
                    },{
                        ccb_title : "More information",
                        ccb_description: 'For any queries in relation to my policy on cookies and your choices, please contact me.',
                    }
                ]
            }
        }
    ]
});

How to open cookie policy without manually calling api

You need to create a button or link with the following custom attribute data-cc="cc_policy"

<!-- button example-->
<button type="button" data-cc="cc_policy">Open cookie-policy</button>

<!-- link example-->
<a href="javascript:void(0)" data-cc="cc_policy">Open cookie-policy</a>

How to enable dark-mode

You can either specifiy the class cc_darkmode on a parent container (for example on body), or you can toggle it manually like in the following example

document.body.classList.toggle('cc_darkmode');

How can I link the cookieconsent to my own cookie policy?

You need to specify the cc_policy_url property with your url, like this:

cc_policy_url : 'https://yourdomain.com/<path>/cookiepolicy'

The second button will be linked to the specified url and you no longer need to set the policy property inside cc_languages.

Note: by choosing this route, you will not benefit of the integrated "opt-in / opt-out" custom preferences for each defined cookie category

Do something on "accept cookie-consent" event

You can find the user cookie settings via the cc_accept_callback callback function which is fired everytime a user accepts the cookie consent or if it is alredy accepted

CookieConsent.run({
    // ...
    cc_accept_callback : function(cookies){
        // print accepted cookie settings
        console.log('cookie-consent accepted: ', cookies);
        
        /*
         * example: do somethings if 'functionality_cookies' is accepted
         */
        if(cookies.level.includes('functionality_cookies')){
            console.log("yoo");
        }
    }
    // ...
});

Config. properties

  • cc_autorun : (boolean)
    • default : false
    • if set to true, cookieconsent will show modal as soon as loaded
  • cc_delay : (number)
    • default : 0
    • if specified (>=0), there will be an initial delay before showing the cookieconsent modal
    • useful when you have implemented a "loader"
  • cc_enable_verbose : (boolean)
    • default : true
    • if set to true, all informational/error messages will show on console
  • cc_current_lang : (string) [REQUIRED]
    • default : "en"
    • when specified, modal will be set to that language (if it is implemented)
  • cc_cookie_expiration : (number) [NEW FROM VERSION 1.2]
    • default : 182
    • number of days before cc_cookie expires
  • cc_autoclear_cookies : (boolean) [NEW FROM VERSION 1.2]
    • default : true
    • if set to true, erases all unused cookies specified inside ccb_cookies_table based the selected preferences inside cookiepolicy modal
  • cc_auto_language : (boolean)
    • default : false
    • if set to true, cc_current_lang will be ignored, and the cookieconsent modal will set its language based on client browser language (if specific client browser language is not defined, a fallback_language="en" will be used instead)
  • cc_autoload_css : (boolean) [NEW FROM VERSION 1.2]
    • default : true
    • if set to true, the plugin will automatically load the specified .css file based on cc_theme_css path
  • cc_theme_css : (string) [REQUIRED]
    • default : null
    • specify path to local cookieconsent.css file
  • cc_policy_url : (string)
  • cc_accept_callback : (function)
    • default : undefined (not used)
    • a function to call when the visitor accepts the cookie consent, or has alredy accepted it
  • cc_languages : (string) [REQUIRED]
    • default : [{<en_language_only>}]
    • define (multiple) new languages or override default one (en)
    • if no languages are defined, an error will be thrown
    • example usage (full example here):
      /*
       * Defining new language example
       * the following props: lang, modal, policy are required
       */
      CookieConsent.run({
          cc_languages : [
              {
                  lang : 'it',	//add italian
                  modal : {
                      cc_title : "<title ...>",
                      // ...
                  },
                  policy : {
                      // ...
                  }
              }
          ]
      });

Support for multi-language website

If you have a multi-language website and you want to be able to dynamically change language of the cookie consent based on the page language (or other dynamic params), you can achieve that by assigning the value to cc_current_lang. In the example below the language is fetched from lang="..." attribute of the <html> tag:

cc_auto_language : false,
// 'en' is used as fallback
cc_current_lang : document.documentElement.getAttribute('lang') || 'en'

Reccomended way of loading the plugin

  1. preload cookieconsent.css inside <head>
    <link rel="preload" href="<your_path>/cookieconsent.css" as="style">
  2. append cookieconsent.js at the bottom, inside body tag
    <script src="<your_path>/cookieconsent.js"></script>
  3. initialize plugin with a config. object like full example

TODO

List of things to implement

  • Add dark-mode
    • can be enabled manually by toggling a specific class
  • Add option to set custom cookie expiration date
  • Make all cookie-modal content and cookie-policy customizable
  • Add the possibility of quickly defining a new language/override default one
  • Implement a dropdown select language menu when multiple languages are defined
  • Custom cookie-policy url (useful for those who alredy have a cookie policy)
  • Make cookieconsent GPDR compliant (up to user):
    • Implement "learn more" modal with a brief explanation about cookies (up to user)
    • Implement custom-cookie-table containing (up to user):
      • column for cookie-name
      • column for cookie-description
      • column for cookie-expiration-date
    • Implement the (eventual) possibility of opting-out of cookie-consent (up to user)

Changelog

  • version 1.2
    - ✨ 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
    
  • version 1.1
    - ✨ add __custom table headers__ in cookie-policy modal
    - ✨ tables inside cookie-policy can now have an arbitrary number of columns defined by user
    - 🔥 refactor code / remove unused code
    - minor css updates
    

About

:cookie: Simple cross-browser cookie-consent plugin written in vanilla js

https://orestbida.com/public/demo-projects/cookieconsent/

License:MIT License


Languages

Language:JavaScript 73.0%Language:CSS 27.0%