Giter VIP home page Giter VIP logo

cookie-consent's Introduction

Cookie Consent

CI status

JavaScript utility library

  • No dependencies
  • Choose between checkbox or radio inputs
  • Customizable cookie types (identifiers, optional/required, pre-checked)
  • Conditional script tags, iframes and elements based on cookie consent and type

Screenshot of the GDPR proof cookie consent dialog from @grrr/cookie-consent with checkbox inputsScreenshot of the GDPR proof cookie consent dialog from @grrr/cookie-consent with radio inputs

Developed with ❤️ by GRRR

Installation

$ npm install @grrr/cookie-consent

Note: depending on your setup additional configuration might be needed. This package is published with untranspiled JavaScript, as EcmaScript Modules (ESM).

Usage

Import the module and initialize it:

import CookieConsent from '@grrr/cookie-consent';

const cookieConsent = CookieConsent({
  cookies: [
    {
      id: 'functional',
      label: 'Functional',
      description: 'Lorem ipsum.',
      required: true,
    },  
    {
      id: 'marketing',
      label: 'Marketing',
      description: 'Lorem ipsum.',
      checked: true,
    },
  ],
});

Conditional scripts

Conditionally show script tags. Add the data-cookie-consent-attribute with the id of the required cookie type, and disable the script by setting the type to text/plain:

// External script.
<script src="https://..." data-cookie-consent="marketing" type="text/plain"></script>

// Inline script.
<script data-cookie-consent="marketing" type="text/plain">
    alert('hello world');
</script>

Conditional iframe embeds

Conditionally show or hide iframe embed. Add the data-cookie-consent-attribute with the id of the required cookie consent type, and disable the iframe renaming the src-attribute to data-src:

<iframe data-cookie-consent="marketing" data-src="https://..."></iframe>

Conditional content

Conditionally show or hide elements. Add the data-cookie-consent-<state>-attribute with the id of the required cookie consent type. There are two types of state: accepted and rejected.

<div data-cookie-consent-accepted="marketing" hidden>Accepted</div>
<div data-cookie-consent-rejected="marketing" hidden>Rejected</div>

Notes:

  • When hiding, the module will add aria-hidden="true" and style="display: none;" to remove it from the DOM.
  • When showing, the module will remove any inline set display style, along with any hidden or aria-hidden attributes.

Options

All options except cookies are optional. They will fall back to the defaults, which are listed here:

{
  type: 'checkbox',         // Can be `checkbox` or `radio`.
  prefix: 'cookie-consent', // The prefix used for styling and identifiers.
  append: true,             // By default the dialog is appended before the `main` tag or
                            // as the first `body` child. Disable to append it yourself.
  appendDelay: 500,         // The delay after which the cookie consent should be appended.
  acceptAllButton: false,   // Nudge users to accept all cookies when nothing is selected.
                            // Will select all checkboxes, or the top radio button.
  cookies: [                // Array with cookie types.
    {
      id: 'marketing',      // The unique identifier of the cookie type.
      label: 'Marketing',   // The label used in the dialog.
      description: '...',   // The description used in the dialog.
      required: false,      // Mark a cookie required (ignored when type is `radio`).
      checked: false,       // The default checked state (only valid when not `required`).
    },
  ],
  // If you need to override the dialog template (default defined in renderDialog)
  dialogTemplate: function(templateVars) {
    return '...'
  },
  // Labels to provide content for the dialog.
  labels: {
    title: 'Cookies & Privacy',
    description: `<p>This site makes use of third-party cookies. Read more in our
                  <a href="/privacy-policy">privacy policy</a>.</p>`,
    // Button labels based on state and preferences.
    button: {
      // The default button label.
      default: 'Save preferences',
      // Shown when `acceptAllButton` is set, and no option is selected.
      acceptAll: 'Accept all',
    },
    // ARIA labels to improve accessibility.
    aria: {
      button: 'Confirm cookie settings',
      tabList: 'List with cookie types',
      tabToggle: 'Toggle cookie tab',
    },
  },
}

API

CookieConsent(options: object)

Will create a new instance.

const cookieConsent = CookieConsent({
    cookies: [
        // ...
    ]
});

To make the instance globally available (for instance to add event listeners elsewhere), add it as a global after the instance has been created:

const cookieConsent = CookieConsent();

window.CookieConsent = cookieConsent;

getDialog()

Will fetch the dialog element, for example to append it at a custom DOM position.

document.body.insertBefore(cookieConsent.getDialog(), document.body.firstElementChild);

showDialog()

Will show the dialog element, for example to show it when triggered to change settings.

el.addEventListener('click', e => {
  e.preventDefault();
  cookieConsent.showDialog();
});

hideDialog()

Will hide the dialog element.

el.addEventListener('click', e => {
  e.preventDefault();
  cookieConsent.hideDialog();
});

isAccepted(id: string)

Check if a certain cookie type has been accepted. Will return true when accepted, false when denied, and undefined when no action has been taken.

const acceptedMarketing = cookieConsent.isAccepted('marketing'); // => true, false, undefined

getPreferences()

Will return an array with preferences per cookie type.

const preferences = cookieConsent.getPreferences();

// [
//   {
//     "id": "analytical",
//     "accepted": true
//   },
//   {
//     "id": "marketing",
//     "accepted": false
//   }
// ]

on(event: string)

Add listeners for events. Will fire when the event is dispatched from the CookieConsent module. See available events.

cookieConsent.on('event', eventHandler);

updatePreference(cookies: array)

Update cookies programmatically.

By updating cookies programmatically, the event handler will receive an update method.

const cookies = [
    {
      id: 'marketing',
      label: 'Marketing',
      description: '...',
      required: false,
      checked: true,
    },
    {
      id: 'simple',
      label: 'Simple',
      description: '...',
      required: false,
      checked: false,
    },
];

cookieConsent.updatePreference(cookies);

Events

Events are bound by the on method.

update

Will fire whenever the cookie settings are updated, or when the instance is constructed and stored preferences are found. It returns the array with cookie preferences, identical to the getPreferences() method.

This event can be used to fire tag triggers for each cookie type, for example via Google Tag Manager (GTM). In the following example trackers are loaded via a trigger added in GTM. Each cookie type has it's own trigger, based on the cookieType variable, and the trigger itself is invoked by the cookieConsent event.

Example:

cookieConsent.on('update', cookies => {
  const accepted = cookies.filter(cookie => cookie.accepted);
  const dataLayer = window.dataLayer || [];
  accepted.forEach(cookie => dataLayer.push({
    event: 'cookieConsent',
    cookieType: cookie.id,
  }));
});

Styling

No styling is being applied by the JavaScript module. However, there is a default stylesheet in the form of a Sass module which can easily be added and customized to your project and its needs.

Stylesheet

View the base stylesheet.

Note: no vendor prefixes are applied. We recommend using something like Autoprefixer to do that automatically.

Interface

With the styling from the base module applied, the interface will look roughly like this (fonts, sizes and margins might differ):

Screenshot of the GDPR proof cookie consent dialog from @grrr/cookie-consent

cookie-consent's People

Contributors

bornemisza avatar countnick avatar hammenws avatar harmenjanssen avatar martijngastkemper avatar martijnnieuwenhuizen avatar milocasagrande avatar mte90 avatar qmeister avatar quent1pr avatar roelandvs avatar schoenkaft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

cookie-consent's Issues

Feature proposal: expose functionality to clean up or migrate old cookie IDs

I noticed during development that when I changed the IDs of cookies, I would get those old cookie IDs back even though I wasn't interested in them.

One way to handle this would be to provide a setting like unrecognizedCookieIdBehavior which could have the values (where "unrecognized cookies" means "cookies having an ID that doesn't exist in the current settings"):

  • "include": includes the unrecognized cookies in .getPreferences and in .on('update')
  • "ignore": does not include unrecognized cookies in .getPreferences and in .on('update'), but also doesn't delete them from the storage
  • "remove": silently removes the unrecognized cookies.
  • a function that takes an array of the cookie values not existing in the current settings, and which returns an array of cookie values that should be migrations of the old cookie IDs to the new cookie IDs. The function can return an array of any number of cookie values, so the function can ignore cookies or expand them into multiple if it wants. If the function returns null, undefined, or false, then it is as if the function returned an empty array. Returning any other value is an error.

Here's an example of the type of workaround I had to implement since something like this functionality is missing:

// I need to use this implementation detail to make the fix myself
const PREFS_LOCAL_STORAGE_KEY = 'cookie-consent-preferences'

const settings = {
  // The dialog flashes even when consent has already been given. So add it ourselves.
  append: false,
  cookies: [
    {
      id: REQUIRED_FUNCTIONALITY,
      label: 'Required functionality',
      description: 'Persists your response to this dialog.',
      required: true,
    },
    ...
  ],
}

export function fixConsentCookieIds() {
  const validIds = keyBy(settings.cookies, 'id')
  const prefs = fromJson(window.localStorage.getItem(PREFS_LOCAL_STORAGE_KEY))
  const newPrefs = []
  forEach(prefs, (pref) => {
    if (!validIds[pref.id]) {
      logger.debug(`dropping invalid cookie consent pref ${toJson(pref)}`)
      return
    }
    newPrefs.push(pref)
  })
  window.localStorage.setItem(PREFS_LOCAL_STORAGE_KEY, toJson(newPrefs))
}

Feature proposal: include the previous version of the cookie in the on('update') callback

I am responding to cookieConsent.on('update') calls to modify my app's state to match the user's current preferences. E.g., if they enable ERROR_REPORTING, I can initialize sentry.

I found this difficult because in order to take the correct actions, I need to know if the cookie value is actually changing or not. Below I have some example code from a React app. My workaround is to persist the cookie state in a Redux store so that I am able to compare new values to old values.

I wanted to get initial feedback on this feature. Is there any apparent reason that it wouldn't be a good idea or would be difficult based upon the library's current implementation? Thanks!

class App extends Component {
  ...
  componentDidMount() {
    ...
    // cookieConsent.on(update) fires when it loads the cookies from storage, so persist them first.
    this.props.privacyConsent.update(cookieConsent.getPreferences())  // stores in redux
    // Load the cookie consent after the update to the Redux store has had a chance to occur.
    setTimeout(() => cookieConsent.on('update', this.onCookieConsentUpdate))
  }
 
 onCookieConsentUpdate = (cookies) => {
    let requiresReload = false
    const privacyConsentState = this.props.privacyConsentState  // was retrieved from redux elsewhere
    forEach(cookies, (cookie) => {
      const prevCookie = privacyConsentState[cookie.id]
      if (prevCookie && cookie.accepted === prevCookie.accepted) {
        // Only process differences
        return
      }
      let requestReload = false
      switch (cookie.id) {
        case REQUIRED_FUNCTIONALITY:
          // Required functionality can't be changed, so there's never anything to do.
          break
        case ERROR_REPORTING:
          if  (cookie.accepted) {
            sentryInit()
          } else {
            // Sentry's beforeSend checks this value before sending events
          }
          break
        case FULL_ERROR_REPORTING:
          requestReload = true
          break
        default:
          logger.error(`Unsupported cookie consent id: ${cookie.id}`)
          // Require reload just to be safe
          requestReload = true
          // It's possible that the user has an old version of the cookie IDs.
          fixConsentCookieIds()
          break
      }
      // Assume that functionality is disabled by default, and so if there is no previous cookie,
      // then we only need a reload if the functionality is now accepted.
      requiresReload = requiresReload || requestReload  && (isTruthy(prevCookie) || cookie.accepted)
    })
    if (requiresReload) {
      this.props.ui.addToast("Please reload the page for changes to take effect.")
    }
    this.props.privacyConsent.update(cookies)  // persist the new cookies
  }

Setting for h1 title tag

Hello,
For SEO purpose, I need to change the h1 tag on this line :

<h1>${config.get('labels.title')}</h1>

What is the best option to do that ? Should we add the heading tag as a configurable option (how to handle the scss) ? Is there any way to override this function ? Should I create a pull request ?

Missing styled-scrollbar scss mixin

Hi, I was to about to try this package, but upon building my assets, it failed on undefined mixin error at line 7 in your scss file. Can you maybe provide mentioned mixin or remove the line?

ERROR in ./resources/sass/frontend/app.scss
Module build failed (from ./node_modules/css-loader/index.js):
ModuleBuildError: Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined mixin.
  ╷
7 │     @include styled-scrollbar;
  │     ^^^^^^^^^^^^^^^^^^^^^^^^^
  ╵

Callback option?

Hey there, thanks so much for this amazing script, it works like a charm! I looked at the docs, but couldn't find it: is there a callback option?

I would love to be able to record whether people accept or reject cookies, it would help explain to my client why his e-commerce analytics are incomplete. :)

Checkbox returns to true after being unchecked

Hi,

const requiredCount = config.get('cookies').filter(c => c.required).length;
    const checkedCount = values.filter(v => v.accepted).length;
    const userOptionsChecked = checkedCount > requiredCount;
    if (ACCEPT_ALL_BUTTON && TYPE === 'checkbox' && !userOptionsChecked) {
      return values.map(value => ({
        ...value,
        accepted: true,
      }));
    }

If you have one setting required and one optional and uncheck the optional, this will compare 1 > 1 leading to re-check the optional.
I think checkedCount >= requiredCount would fix it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.