Coder Social home page Coder Social logo

grrr-amsterdam / cookie-consent Goto Github PK

View Code? Open in Web Editor NEW
64.0 7.0 11.0 247 KB

Cookie consent with accessible dialog, agnostic tag triggers and conditional content, script and embed hooks.

License: MIT License

JavaScript 81.96% SCSS 18.04%
cookies cookie-consent cookie-banner gdpr gdpr-consent hacktoberfest-accepted

cookie-consent's Introduction

Cookie Consent

CI status

JavaScript utility library

  • No dependencies
  • 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 inputs

Developed with ❤️ by GRRR

Installation

$ npm install @grrr/cookie-consent

Custom element

This cookie-consent module is a custom element. This also means that the element is encapsulated in a shadow DOM. Here follows some information of how to implement this custom element in your own project.

Usage

Import the module and register it as a custom element:

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

if (window.customElements.get("cookie-consent") === undefined) {
    window.customElements.define("cookie-consent", cookieConsent);
}

Once registered, you can add the cookie-consent element to your HTML there's some optional data you can pass to the element but the only required attribute to pass along are the cookies:

const cookies = [
    {
        id: "functional", // string
        label: functionalCookiesLabel, // string
        description: functionalCookiesDescription, // string
        required: true, // boolean
    },
    {
        id: "marketing", // string
        label: marketingCookiesLabel, // string
        description: marketingCookiesDescription, // string
        checked: marketingCookiesAccepted, // boolean
    },
];
// in order to pass these as a data-attribute we'll need to transform them to a string first
const stringifiedCookies = JSON.stringify(cookies);
<cookie-consent data-cookies="cookies" />;

Options

As mentioned before there is some optional data you can pass to the element:

  • title string
  • description string
  • save button text string

To use the options, add them as data attributes to the custom element:

<cookie-consent
    data-title="Cookies & Privacy" // The title of the dialog.
    data-description="<p>This site makes use of third-party cookies.
    Read more in our <a href='/privacy-policy'>privacy policy</a>.</p>"  // The description of the dialog.
    data-saveButtonText="Save preferences" // The save button label.
    data-cookies=cookies
/>

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

export const DEFAULTS = {
    prefix: "cookie-consent",
    append: true,
    appendDelay: 500,
    acceptAllButton: false,
    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: {
            default: "Save preferences",
            acceptAll: "Accept all",
        },
        aria: {
            button: "Confirm cookie settings",
            tabList: "List with cookie types",
            tabToggle: "Toggle cookie tab",
        },
    },
};

API

show()

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

button.addEventListener("click", (e) => {
    e.preventDefault();
    cookieConsent.show();
});

hide()

Will hide the dialog element.

button.addEventListener("click", (e) => {
    e.preventDefault();
    cookieConsent.hide();
});

getPreferences()

Will return an array with preferences per cookie type.

const preferences = cookieConsent.getPreferences();

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

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,
    },
];

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);

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.

You have to use the ::parts pseudo-element to style the dialog and its elements due to the Shadow DOM encapsulation. You can style the dialog and its elements by using the following parts:

cookie-consent::part(cookie-consent) {
    // Styles for the cookie consent dialog
}

/**
 * Header
 */
cookie-consent::part(cookie-consent__header) {
    // Styles for the cookie consent header
}
cookie-consent::part(cookie-consent__title) {
    // Styles for the cookie consent title
}

/**
 * Tabs
 */
cookie-consent::part(cookie-consent__tab-list) {
    // Styles for the cookie consent tab list
}
cookie-consent::part(cookie-consent__tab-list-item) {
    // Styles for the cookie consent tab list item
}
cookie-consent::part(cookie-consent__tab) {
    // Styles for the cookie consent tabs
}

/**
 * Tab option (label with input in it) & tab toggle
 */
cookie-consent::part(cookie-consent__option) {
    // Styles for the tab option label
}
cookie-consent::part(cookie-consent__input) {
    // Styles for the tab option input
}
cookie-consent::part(cookie-consent__tab-toggle) {
    // Styles for the tab toggle
}
cookie-consent::part(cookie-consent__tab-toggle-icon) {
    // Styles for the tab toggle icon
}

/**
 * Tab panel (with description)
 */
cookie-consent::part(cookie-consent__tab-panel) {
    // Styles for the tab panel
}

cookie-consent::part(cookie-consent__tab-description) {
    // Styles for the tab description
}

/**
 * Button
 */
cookie-consent::part(cookie-consent__button) {
    // styles for the consent button
}
cookie-consent::part(cookie-consent__button-text) {
    // Styles for the consent button text
}

Stylesheet

View the base stylesheet.

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 with checkbox inputs

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: 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
  }

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.

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. :)

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))
}

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;
  │     ^^^^^^^^^^^^^^^^^^^^^^^^^
  ╵

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 ?

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.