Socket
Socket
Sign inDemoInstall

vanilla-cookieconsent

Package Overview
Dependencies
0
Maintainers
1
Versions
43
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

vanilla-cookieconsent


Version published
Weekly downloads
37K
decreased by-34.33%
Maintainers
1
Install size
408 kB
Created
Weekly downloads
 

Readme

Source

Forked to publish in the NPM registry. No further changes. Thanks and credits to Orest Bida.


A lightweight & gdpr compliant cookie consent plugin written in plain javascript. An "all-in-one" solution which also allows you to write your cookie policy inside it without the need of having a dedicated page.

Cookie Consent cover Cookie Consent cover

Table of contents

  1. Key features
  2. How to use
  3. Download & CDN
  4. Layout options & customization
  5. APIs & config. parameters
  6. Manage third party scripts
  7. Configuration examples (work-in-progress)
  8. How to enable/manage revisions
  9. FAQ
  10. License

Key features

  • Lightweight
  • Cross-browser support (IE8+)
  • Standalone (no external dependencies needed)
  • GDPR compliant
  • Support for multi language
  • WAI-ARIA compliant
  • Allows you to define different cookie categories with opt in/out toggle
  • Allows you to define custom cookie tables if you want to clarify the cookies you use

How to use

  1. Download (or use via cdn) and include the script at the bottom of body tag.

    <script src="<path-to-cookieconsent.js>"></script>
    
  2. Run the plugin with your configuration parameters. IMPORTANT: you must provide at least the following parameters: current_lang and languages

    Show basic example
    <script src="<path-to-cookieconsent.js>"></script>
    <script>
        var cookieconsent = initCookieConsent();
    
        cookieconsent.run({
            current_lang : 'en',
            theme_css : '<path-to-cookieconsent.css>',
    
            onAccept : function(){
                // do something ...
            },
    
            languages : {
                en : {
                    consent_modal : {
                        title :  "I use cookies",
                        description :  'Your cookie consent message here',
                        primary_btn: {
                            text: 'Accept',
                            role: 'accept_all'  //'accept_selected' or 'accept_all'
                        },
                        secondary_btn: {
                            text : 'Reject',
                            role : 'accept_necessary'   //'settings' or 'accept_necessary'
                        }
                    },
                    settings_modal : {
                        title : 'Cookie settings',
                        save_settings_btn : "Save settings",
                        accept_all_btn : "Accept all",
                        reject_all_btn : "Reject all", // optional, [v.2.5.0 +]
                        close_btn_label: "Close",   
                        blocks : [
                            {
                                title : "Cookie usage",
                                description: 'Your cookie usage disclaimer'
                            },{
                                title : "Strictly necessary cookies",
                                description: 'Category description ... ',
                                toggle : {
                                    value : 'necessary',
                                    enabled : false,
                                    readonly: true
                                }
                            },{
                                title : "Analytics cookies",
                                description: 'Category description ... ',
                                toggle : {
                                    value : 'analytics',
                                    enabled : false,
                                    readonly: false
                                }
                            },
                        ]
                    }
                }
            }
        });
    </script>
    

    For more details check out full examples and how to configure languages & cookie settings sections.

Download & CDN

You can download the latest version or use it via cdn:

javascript :

https://cdn.jsdelivr.net/gh/orestbida/cookieconsent@v2.5.0/dist/cookieconsent.js

stylesheet :

https://cdn.jsdelivr.net/gh/orestbida/cookieconsent@v2.5.0/dist/cookieconsent.css

Layout options & customization

You can change the color scheme with css variables inside cookieconsent.css. You can also change some basic layout options via the gui_options inside the config. object; example:

cookieconsent.run({
    ...
    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
        }
    }
    ...
});

Default layout is box and default transition is zoom.

Manage third party scripts

If you have <script> tags which you want to manage through the cookieconsent (enable based on a specific cookie category) you can do this by either moving the javascript code inside the onAccept/onChange methods and using the provided APIs below, or via page_scripts option:

  1. Enable page scripts management:

    cookieconsent.run({
        ...
        page_scripts: true
        ...
    });
    
  2. Disable the script tag by setting type="text/plain" and change src to data-src:

    <script type="text/plain" data-src="<path>/analytics.js" defer>
    
  3. Add data-cookiecategory attribute:

    <script type="text/plain" data-src="<path>/analytics.js" data-cookiecategory="analytics" defer>
    

    Note: data-cookiecategory must also be defined inside the config. object

APIs & configuration parameters

After getting the plugin like so:

var cookieconsent = initCookieConsent();

the following methods are available:

  • cookieconsent.run(<config_object>)
  • cookieconsent.show(<optional_delay>)
  • cookieconsent.hide()
  • cookieconsent.showSettings(<optional_delay>)
  • cookieconsent.hideSettings()

Additional methods for an easier management of your scripts and cookie settings (expand them to see usage example):

  • cookieconsent.accept(<accepted_categories>, <optional_rejected_categories>) [v2.5.0+]

    • accepted_categories: string or string[]
    • rejected_categories: string[] - optional

    Note: all categories marked as readonly will ALWAYS be enabled/accepted regardless of the categories provided inside the .accept() API call.

    Examples:

    cookieconsent.accept('all');                // accept all categories
    cookieconsent.accept([]);                   // accept none (reject all)
    cookieconsent.accept('analytics');          // accept only analytics category
    cookieconsent.accept(['cat_1', 'cat_2']);   // accept only these 2 categories   
    cookieconsent.accept();                     // accept all currently selected categories inside modal
    
    cookieconsent.accept('all', ['analytics']); // accept all except "analytics" category
    cookieconsent.accept('all', ['cat_1', 'cat_2']); // accept all except these 2 categories
    

    How to later reject a specific category (cookieconsent already accepted)? Same as above:

    cookieconsent.accept('all', ['targeting']);     // opt out of targeting category
    

  • cookieconsent.allowedCategory(<category_name>)

    Note: there are no default cookie categories, you create them!

    A cookie category corresponds to the string of the value property inside the toggle object:

    ...    
    toggle : {
        value: 'analytics',     // cookie category
        enabled : false,        // default status
        readonly: false         // allow to enable/disable
        // reload : 'on_disable',   // allows to reload page when the current cookie category is deselected
    }
    ...
    

    Example:

    // Check if user accepts cookie consent with analytics category enabled
    if(!cookieconsent.allowedCategory('analytics')){
        // yoo, you might want to load analytics.js ...
    };
    

  • cookieconsent.validCookie(<cookie_name>)

    If cookie exists and has non empty ('') value => return true, otherwise false.

    // Example: check if '_gid' cookie is set
    if(!cookieconsent.validCookie('_gid')){
        // yoo, _gid cookie is not set, do something ...
    };
    

  • cookieconsent.eraseCookies(<cookie_names>, <optional_path>, <optional_domains>) [v2.5.0+]

    • cookie_names: string[]
    • path: string - optional
    • domains: string[] - optional

    Examples:

    cookieconsent.eraseCookies(['cc_cookies']);             // erase "cc_cookie" if it exists
    cookieconsent.eraseCookies(['cookie1', 'cookie2']);     // erase these 2 cookies
    
    cookieconsent.eraseCookies(['cc_cookie'], "/demo");
    cookieconsent.eraseCookies(['cc_cookie'], "/demo", [location.hostname]);
    

  • cookieconsent.loadScript(<path>, <callback_function>, <optional_custom_attributes>)

    Basic example:

    cookieconsent.loadScript('https://www.google-analytics.com/analytics.js', function(){
        // Script loaded, do something
    });
    

    How to load scripts with custom attributes:

    cookieconsent.loadScript('https://www.google-analytics.com/analytics.js', function(){
        // Script loaded, do something
    }, [
        {name: 'id', value: 'ga_id'},
        {name: 'another-attribute', value: 'value'}
    ]);
    

All available options

Below a table which sums up all of the available options (must be passed to the .run() method).

OptionTypeDefaultDescription
autorunbooleantrueIf enabled, show the cookie consent as soon as possible (otherwise you need to manually call the .show() method)
delaynumber0Number of milliseconds before showing the consent-modal
cookie_expirationnumber182Number of days before the cookie expires (182 days = 6 months)
cookie_pathstring"/"Path where the cookie will be set
cookie_domainstringlocation.hostnameSpecify your domain (will be grabbed by default) or a subdomain
cookie_same_sitestring"Lax"SameSite attribute
theme_cssstring-Specify path to the .css file
force_consentbooleanfalseEnable if you want to block page navigation until user action (check faq for a proper implementation)
revisionnumber0Specify this option to enable revisions. Check below for a proper usage
current_langstring-Specify one of the languages you have defined (can also be dynamic): 'en', 'de' ...
auto_languagebooleanfalseAutomatically grab the language based on the user's browser language, if language is not defined => use specified current_lang
autoclear_cookiesbooleanfalseEnable if you want to automatically delete cookies when user opts-out of a specific category inside cookie settings
page_scriptsbooleanfalseEnable if you want to easily manage existing <script> tags. Check manage third party scripts
remove_cookie_tablesbooleanfalseEnable if you want remove the html cookie tables (and still want to make use of autoclear_cookies)
gui_optionsobject-Customization option which allows to choose layout, position and transition. Check layout options & customization
onAcceptfunction-Method run once either when:
1. The moment the cookie consent is accepted
2. After each page load (if cookie consent has already been accepted)
onChangefunction-Method run whenever preferences are modified (and only if cookie consent has already been accepted)
languagesobject-Check below for configuration

Full example configurations

  • Configuration with google analytics

    // obtain cookieconsent plugin
    var cc = initCookieConsent();
    
    // run plugin with config object
    cc.run({
        autorun : true, 							
        delay : 0,
        current_lang : 'en',
        theme_css : "../src/cookieconsent.css",		
        autoclear_cookies : true,	
        cookie_expiration : 365,
        
        gui_options : {
            consent_modal : {
                layout : 'cloud',
                position : 'bottom',
                transition : 'slide'
            },
            settings_modal : {
                layout : 'box',
                transition : 'slide'
            }
        },
        
        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');
                });
            }
        },
        
        languages : {
            en : {	
                consent_modal : {
                    title :  "I use cookies",
                    description :  'Hi, this website uses essential cookies to ensure its proper operation and tracking cookies to understand how you interact with it. The latter will be set only upon approval. <a aria-label="Cookie policy" class="cc-link" href="#">Read more</a>',
                    primary_btn: {
                        text: 'Accept',
                        role: 'accept_all'				//'accept_selected' or 'accept_all'
                    },
                    secondary_btn: {
                        text : 'Settings',
                        role : 'settings'				//'settings' or 'accept_necessary'
                    }
                },
                settings_modal : {
                    title : 'Cookie preferences',
                    save_settings_btn : "Save settings",
                    accept_all_btn : "Accept all",
                    reject_all_btn : "Reject all",      // optional, [v.2.5.0 +]
                    cookie_table_headers : [
                        {col1: "Name" }, 
                        {col2: "Domain" }, 
                        {col3: "Expiration" }, 
                        {col4: "Description" }, 
                        {col5: "Type" }
                    ],
                    blocks : [
                        {
                            title : "Cookie usage",
                            description: 'I use cookies 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.'
                        },{
                            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_cookies',
                                enabled : true,
                                readonly: true
                            }
                        },{
                            title : "Analytics cookies",
                            description: 'These cookies collect information about how you use the website, which pages you visited and which links you clicked on. All of the data is anonymized and cannot be used to identify you.',
                            toggle : {
                                value : 'analytics_cookies',
                                enabled : false,
                                readonly: false
                            },
                            cookie_table: [
                                {
                                    col1: '_ga',
                                    col2: 'google.com',
                                    col3: '2 years',
                                    col4: 'description ...' ,
                                    col5: 'Permanent cookie'
                                },
                                {
                                    col1: '_gat',
                                    col2: 'google.com',
                                    col3: '1 minute',
                                    col4: 'description ...' ,
                                    col5: 'Permanent cookie'
                                },
                                {
                                    col1: '_gid',
                                    col2: 'google.com',
                                    col3: '1 day',
                                    col4: 'description ...' ,
                                    col5: 'Permanent cookie'
                                }
                            ]
                        },{
                            title : "More information",
                            description: 'For any queries in relation to my policy on cookies and your choices, please <a class="cc-link" href="#yourwebsite">contact me</a>.',
                        }
                    ]
                }
            }
        }
    });
    

  • More to be added ...

Languages is an object which basically holds all of the text/html of your cookie modals in different languages. In here you can define cookie categories, cookie tables, opt-in/out toggle for each category and more. For each language, a consent_modal object and a settings_modal object must be configured.

Example with multiple languages ('en' and 'it')

cookieconsent.run({
    ...
    languages : {
        'en' : {
            consent_modal : {
                title :  "Title here ...",
                description :  'Description here ...',
                primary_btn: {
                    text: 'Accept',
                    role: 'accept_all'      //'accept_selected' or 'accept_all'
                },
                secondary_btn: {
                    text : 'Settings',
                    role : 'settings'       //'settings' or 'accept_necessary'
                }
            },
            settings_modal : {
                title : 'Cookie preferences ...',
                save_settings_btn : "Save settings",
                accept_all_btn : "Accept all",
                blocks : [
                    {
                        title : "First block title ...",
                        description: 'First block description ...'
                    },{
                        title : "Second block title ...",
                        description: 'Second block description ...',
                        toggle : {
                            value : 'my_category1',
                            enabled : true,
                            readonly: true
                        }
                    },{
                        title : "Third block title ...",
                        description: 'Third block description ...',
                        toggle : {
                            value : 'my_category2',
                            enabled : false,
                            readonly: false
                        }
                    }
                ]
            }
        },
        'it' : {
            consent_modal : {
                title :  "Title in italian here ...",
                description :  'Description in italian here ...',
                primary_btn: {
                    text: 'Accept in italian',
                    role: 'accept_all'				//'accept_selected' or 'accept_all'
                },
                secondary_btn: {
                    text : 'Settings',
                    role : 'settings'				//'settings' or 'accept_necessary'
                }
            },
            settings_modal : {
                title : 'Cookie preferences ...',
                save_settings_btn : "Save settings in italian",
                accept_all_btn : "Accept all",
                blocks : [
                    {
                        title : "First block title in italian ...",
                        description: 'First block description in italian ...'
                    },{
                        title : "Second block title in italian ...",
                        description: 'Second block description in italian...',
                        toggle : {
                            value : 'my_category1',
                            enabled : true,
                            readonly: true
                        }
                    },{
                        title : "Third block title in italian ...",
                        description: 'Third block description in italian...',
                        toggle : {
                            value : 'my_category2',
                            enabled : false,
                            readonly: false
                        }
                    }
                ]
            }
        }
    }
});

Example with custom cookie table

You can create tables with a custom number of columns to explain what each cookie does.

NOTE: If you want to also use autoclear_cookie, make sure the first column of the cookie table contains the name of the cookie.

Check demo app.js which has a full example with cookie table.

Example with explicit accept all and accept necessary buttons

cookieconsent.run({
    ...
    languages : {
        'en' : {
            consent_modal : {
                title :  "Title here ...",
                description :  'Description here ...',
                primary_btn: {
                    text: 'Accept all',
                    role: 'accept_all'          //'accept_selected' or 'accept_all'
                },
                secondary_btn: {
                    text : 'Accept necessary',
                    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",   // optional, [v.2.5.0 +]
                blocks : [
                    {
                        title : "First block title ...",
                        description: 'First block description ...'
                    },{
                        title : "Second block title ...",
                        description: 'Second block description ...',
                        toggle : {
                            value : 'my_category1',
                            enabled : true,
                            readonly: true
                        }
                    },{
                        title : "Third block title ...",
                        description: 'Third block description ...',
                        toggle : {
                            value : 'my_category2',
                            enabled : true,
                            readonly: false
                        }
                    }
                ]
            }
        }
    }
});

How to enable/manage revisions

  • default revision number is 0
  • if saved revision number inside the existing cookie is different from the one you just specified => consent modal will be shown.
  1. Enable revisions by specifying a valid revision parameter:

    cookieconsent.run({
        ...
        revision: 1,
        ...
    })
    
  2. Set a valid revision_message parameter (optional) inside consent_modal, and put the following placeholder {{revision_message}} somewhere inside description:

    cookieconsent.run({
        ...
        revision: 1,
        ...
        languages : {
            en : {
                consent_modal : {
                    ...
                    description: "Usual description ... {{revision_message}}",
                    revision_message: "<br> Dude, my terms have changed. Sorry for bothering you again!",
                    ...
                },
                ...
            }
        }
        ...
    })
    

FAQ

  • How to enable dark-mode

    Either manually add the following class c_darkmode to the body/html tag, or toggle it via javascript:

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

  • How to add link/button to open cookie settings

    Create a link (or button) with data-cc="c-settings" attribute:

    <a href="javascript:void(0);" aria-label="View cookie settings" data-cc="c-settings">Cookie Settings</a>
    

  • How to integrate with my multi-language website

    If you have multiple versions of your html page, each with a different <html lang="..." > attribute, you can grab this value using:

    document.documentElement.getAttribute('lang');
    

    and then set it as current_lang value like this:

    cookieconsent.run({
        ...
        current_lang : document.documentElement.getAttribute('lang'),
        ...
    });
    

    Note: make sure that the lang attribute's value format (example: 'en' => 2 characters) is identical to the ones you defined. If you have 'en-US' as lang attribute, make sure to also specify 'en-US' (and not just 'en') in the config. parameters.

  • How to load scripts after a specific cookie category has been accepted

    You would do something like this:
    cookieconsent.run({
        ...
        onAccept : function(){
            // if analytics category has been accepted
            if(cookieconsent.allowedCategory('analytics')){
                cookieconsent.loadScript('https://www.google-analytics.com/analytics.js', function(){
                    ga('create', 'UA-XXXXXXXX-Y', 'auto');
                    ga('send', 'pageview');
                });
            }
    
            if(cookieconsent.allowedCategory('marketing')){
                // do something else
            }
        }
    });
    

  • How to autoload the .css file

    You need to set theme_css to a valid path.

    cookieconsent.run({
        ...
        theme_css : "../src/cookieconsent.css",					
        ...
    });
    

  • How to add a "reject all" button inside settings modal

    You need to specify reject_all_btn inside settings_modal:

    cookieconsent.run({
        ...
        languages : {
            en : {
                ...
                settings_modal : {
                    ...
                    reject_all_btn : "Reject all",
                    ...
                }
            }
        } 
    })       
    

  • Make consent required (block page navigation until action)

    This is a css only solution:

    1. enable force_consent option:
      cookieconsent.run({
          ...
          force_consent : true, 				
          ...
      });
      
    2. That should do it. If you want to remove the weird horizontal jump (due to the scrollbar disappearing) you can add the following style inside the head tag of your page:
      <style>
          html,
          body{
              height: auto!important;
              width: 100vw!important;
              overflow-x: hidden!important;
          }
      </style>
      

    For a full example check the second demo.

  • How to create custom cookie tables

    • Cookie tables are defined by you, that is you choose how many columns and what their naming will be

    • Make sure that the first column of the table contains the name of the cookie for autoclear_cookie to work properly


    1. Specify the table structure via the cookie_table_headers property inside settings_modal object:

      Example with 3 columns:

      ...
      cookie_table_headers : [
          {col1: "Name" }, 
          {col2: "Source" }, 
          {col3: "Description" }, 
      ]
      ...
      
    2. Now you can create a cookie_table array of objects:

      ...
      cookie_table: [
          {
              col1: '_ga',
              col2: 'google.com',
              col3: 'description ..',
          },
          {
              col1: '_gid',
              col2: 'google.com',
              col3: 'description ..',
          }
      ]
      ...
      

    Check the examples above for a valid implementation.

License

Distributed under the MIT License. See LICENSE for more information.

Keywords

FAQs

Last updated on 29 Aug 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc