Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@porscheofficial/cookie-consent-banner

Package Overview
Dependencies
Maintainers
2
Versions
21
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@porscheofficial/cookie-consent-banner

<img src="https://github.com/porscheofficial/cookie-consent-banner/raw/main/assets/logo.svg" alt="" width="200" heigh

  • 4.0.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
2.5K
decreased by-26.09%
Maintainers
2
Weekly downloads
 
Created
Source

The Cookie Consent Banner is implemented as Web Component and additionally exported as React Component. This guide explains how to use the Web Component.

Click here to have a look on the documentation of the React Component. Make sure to also have a look on the main repository.


:spiral_notepad: Usage

Installation

Either install via a package manager, or include the component through one of the various npm delivery networks (skypack, unpkg,..).

// yarn
yarn add @porscheofficial/cookie-consent-banner
// or npm
npm i @porscheofficial/cookie-consent-banner --S
<script
  type="module"
  src="https://unpkg.com/@porscheofficial/cookie-consent-banner@1.0.0/dist/cookie-consent-banner/cookie-consent-banner.esm.js"
></script>

Attributes

Attribute (Web Component)DefaultTypeDescription
available-categories[]CategoryItem[]Provide the available Categories. See Real World example
cookie-attributes{path: "/",expires: 7,domain: document.location.hostname}CookieAttributesCustomization of the cookie attributes for the consent cookie (expires can either be a number of days or a Date object).
cookie-name"cookies_accepted_categories"string
disable-reset-site-cookies-on-consent-withdrawnfalsebooleanPrevent cookies from being deleted automatically if consent of the user changed.
disable-slide-in-animationfalsebooleanDisable slide-in animation of banner (See #7)
headlineundefinedstring
btn-label-accept-and-continueundefinedstring
btn-label-select-all-and-continueundefinedstring
btn-label-only-essential-and-continueundefinedstring
btn-label-persist-selection-and-continueundefinedstring
content-settings-descriptionundefinedstring

Events Dispatched by the Component

EventDescription
cookie_consent_preferences_restoredConsent Settings have been saved previously and are now restored on Page Load.
cookie_consent_preferences_updatedConsent Settings have been updated. Either initially set or changed.

Events Receivable by the Component

It's possible to send JavaScript Events to control the banner.

EventDescription
cookie_consent_showShow the the Consent Banner.
cookie_consent_details_showShow the detailed settings (categories). Also the Consent Banner is shown if not done already.

In order to allow the user to always update its preferences it's possible to trigger the banner by sending an event:

<a href="javascript:document.dispatchEvent(new Event('cookie_consent_show'))">
  Show Cookie Settings
</a>

Styling

Styling can be done in two different ways: Either via the availabe CSS Properties or via the CSS ::part pseudo-element.

Styling with CSS Properties

The appearance of the component can be influenced by updating the availabe CSS Properties. In most cases this is enough customization flexibility but since not every aspect is exposed, you might want to use the ::part selectors if you need more flexibility.

<style>
  :root {
    /* COLORS */
    --cookie-consent-banner-colors-primary: #81c784;
    --cookie-consent-banner-colors-primary-border: #81c784;
    --cookie-consent-banner-colors-primary-content: #fff;
    --cookie-consent-banner-colors-secondary: transparent;
    --cookie-consent-banner-colors-secondary-border: #fff;
    --cookie-consent-banner-colors-secondary-content: #fff;
    --cookie-consent-banner-colors-background-body: rgba(25, 31, 34, 0.92);
    --cookie-consent-banner-colors-text: #fff;

    /* BORDER-RADIUS */
    --cookie-consent-banner-border-radius-buttons: 1rem;
    --cookie-consent-banner-border-radius-body: 0;

    /* SPACINGS */
    --cookie-consent-banner-spacings-container-padding-top: 1rem;
    --cookie-consent-banner-spacings-container-padding-left: 1rem;
    --cookie-consent-banner-spacings-container-padding-bottom: 1rem;
    --cookie-consent-banner-spacings-container-padding-right: 1rem;

    --cookie-consent-banner-spacings-body-padding-top: 0;
    --cookie-consent-banner-spacings-body-padding-left: 2rem;
    --cookie-consent-banner-spacings-body-padding-bottom: 0;
    --cookie-consent-banner-spacings-body-padding-right: 2rem;

    /* Z-INDEX */
    --cookie-consent-banner-z-index-container: 99;

    /* FONTS */
    --cookie-consent-banner-font-family-headline: inherit;
    --cookie-consent-banner-font-size-headline: 1.5rem;
    --cookie-consent-banner-font-family-body: inherit;
    --cookie-consent-banner-font-size-body: 0.875rem;
  }
</style>
Styling with the ::part selectors

For full control over the styles we provide you these CSS parts to customize completely by your own:

  1. cookie-consent-banner::part(button-accept-all) for styling the primary button which triggers "Accept All Cookies"
  2. cookie-consent-banner::part(button-persist-selection) for styling the secondary button which triggers "Save Selection"
  3. cookie-consent-banner::part(button-essential-only) for styling the secondary button which triggers "Only required Cookies"
  4. cookie-consent-banner::part(checkbox) for styling the checkboxes
  5. cookie-consent-banner::part(description-main) for styling the main description text
  6. cookie-consent-banner::part(description-settings) for styling the description text on the expanded settings
  7. cookie-consent-banner::part(headline) for styling the headline
<style>
  cookie-consent-banner::part(primary-button) {
    text-transform: uppercase;
  }

  cookie-consent-banner::part(secondary-button) {
    text-transform: uppercase;
    box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);
  }

  cookie-consent-banner::part(checkbox) {
    accent-color: rgb(24, 251, 107);
  }

  cookie-consent-banner::part(description),
  cookie-consent-banner::part(headline) {
    font-family: "Arial", sans-serif;
  }
</style>

:rocket: Real World Examples

...with Tag Manager

This example shows how the component could be integrated into your web application by leveraging the features of a tag manager. The tag manager is not loaded as long as there is no consent given. Once the visitor stores the consent settings, two things happen: The consent data is stored as a cookie cookies_accepted_categories and the tag manager is initialized. Have a look on the main repository for an example consent flow.

<!-- Import Web Component -->
<script
  type="module"
  src="https://unpkg.com/@porscheofficial/cookie-consent-banner@2.1.0/dist/cookie-consent-banner/cookie-consent-banner.esm.js"
></script>
<!-- Update Styles-->
<style>
  :root {
    --cookie-consent-banner-z-index-container: 101;
    --cookie-consent-banner-colors-primary: rgba(0, 255, 255, 0.82);
    --cookie-consent-banner-colors-primary-border: var(
      --cookie-consent-banner-colors-primary
    );
    --cookie-consent-banner-colors-primary-content: #fff;

    --cookie-consent-banner-border-radius-buttons: 100px;
    --cookie-consent-banner-border-radius-body: 0;

    --cookie-consent-banner-spacings-container-padding-top: 0;
    --cookie-consent-banner-spacings-container-padding-left: 0;
    --cookie-consent-banner-spacings-container-padding-bottom: 0;
    --cookie-consent-banner-spacings-container-padding-right: 0;
  }
</style>

<!-- Init Web Component -->
<cookie-consent-banner
  btn-label-accept-and-continue="Agree and continue"
  btn-label-only-essential-and-continue="Continue with technically required cookies only"
  btn-label-persist-selection-and-continue="Save selection and continue"
  btn-label-select-all-and-continue="Select all and continue"
  content-settings-description="You can decide which cookies are used by selecting the respective options below. Please note that your selection may impair in the functionality of the service."
>
  We use cookies and similar technologies to provide certain features, enhance
  the user experience and deliver content that is relevant to your interests.
  Depending on their purpose, analysis and marketing cookies may be used in
  addition to technically necessary cookies. By clicking on "Agree and
  continue", you declare your consent to the use of the aforementioned cookies.
  <a
    href="javascript:document.dispatchEvent(new Event('cookie_consent_details_show'))"
  >
    Here
  </a>
  you can make detailed settings or revoke your consent (in part if necessary)
  with effect for the future. For further information, please refer to our
  <a href="/privacy-policy">Privacy Policy</a>
  .
</cookie-consent-banner>

<!-- Open Banner again -->
<a href="javascript:document.dispatchEvent(new Event('cookie_consent_show'))">
  Show Cookie Consent Settings
</a>

<!-- Scripts -->
<script>
  /* Update available Cookie Categories */
  const cookieConsentBannerElement = document.querySelector(
    "cookie-consent-banner"
  );
  cookieConsentBannerElement.availableCategories = [
    {
      description:
        "Enable you to navigate and use the basic functions and to store preferences.",
      key: "technically_required",
      label: "Technically necessary cookies",
      isMandatory: true,
    },
    {
      description:
        "Enable us to determine how visitors interact with our service in order to improve the user experience.",
      key: "analytics",
      label: "Analysis cookies",
    },
    {
      description:
        "Enable us to offer and evaluate relevant content and interest-based advertising.",
      key: "marketing",
      label: "Marketing cookies",
    },
  ];

  /* Init Tag Manager */
  function loadTagManager() {
    if (typeof google_tag_manager !== "undefined") return; // load only once
    const gTags = function (w, d, s, l, i) {
      w[l] = w[l] || [];
      w[l].push({
        "gtm.start": new Date().getTime(),
        event: "gtm.js",
      });
      let f = d.getElementsByTagName(s)[0],
        j = d.createElement(s),
        dl = l != "dataLayer" ? "&l=" + l : "";
      j.async = true;
      j.src = "https://www.googletagmanager.com/gtm.js?id=" + i + dl;
      f.parentNode.insertBefore(j, f);
    };

    gTags(window, document, "script", "dataLayer", "GTM-XXX");
  }
  window.addEventListener(
    "cookie_consent_preferences_restored",
    loadTagManager
  );
  window.addEventListener("cookie_consent_preferences_updated", loadTagManager);
</script>

...without Tag Manager

This example shows how the component could be integrated into your web application without leveraging the features of a tag manager. The scripts are not loaded as long as there is no consent given. Once the visitor stores the consent settings, two things happen: The consent data is stored as a cookie cookies_accepted_categories and the script elements are added to the page.

<!-- Import Web Component -->
<script
  type="module"
  src="https://unpkg.com/@porscheofficial/cookie-consent-banner@2.1.0/dist/cookie-consent-banner/cookie-consent-banner.esm.js"
></script>
<!-- Update Styles-->
<style>
  :root {
    --cookie-consent-banner-z-index-container: 101;
    --cookie-consent-banner-colors-primary: rgba(0, 255, 255, 0.82);
    --cookie-consent-banner-colors-primary-border: var(
      --cookie-consent-banner-colors-primary
    );
    --cookie-consent-banner-colors-primary-content: #fff;

    --cookie-consent-banner-border-radius-buttons: 100px;
    --cookie-consent-banner-border-radius-body: 0;

    --cookie-consent-banner-spacings-container-padding-top: 0;
    --cookie-consent-banner-spacings-container-padding-left: 0;
    --cookie-consent-banner-spacings-container-padding-bottom: 0;
    --cookie-consent-banner-spacings-container-padding-right: 0;
  }
</style>

<!-- Init Web Component -->
<cookie-consent-banner
  btn-label-accept-and-continue="Agree and continue"
  btn-label-only-essential-and-continue="Continue with technically required cookies only"
  btn-label-persist-selection-and-continue="Save selection and continue"
  btn-label-select-all-and-continue="Select all and continue"
  content-settings-description="You can decide which cookies are used by selecting the respective options below. Please note that your selection may impair in the functionality of the service."
>
  We use cookies and similar technologies to provide certain features, enhance
  the user experience and deliver content that is relevant to your interests.
  Depending on their purpose, analysis and marketing cookies may be used in
  addition to technically necessary cookies. By clicking on "Agree and
  continue", you declare your consent to the use of the aforementioned cookies.
  <a
    href="javascript:document.dispatchEvent(new Event('cookie_consent_details_show'))"
  >
    Here
  </a>
  you can make detailed settings or revoke your consent (in part if necessary)
  with effect for the future. For further information, please refer to our
  <a href="/privacy-policy">Privacy Policy</a>
  .
</cookie-consent-banner>

<!-- Open Banner again -->
<a href="javascript:document.dispatchEvent(new Event('cookie_consent_show'))">
  Show Cookie Consent Settings
</a>

<script>
  /* Update available Cookie Categories */
  const cookieConsentBannerElement = document.querySelector(
    "cookie-consent-banner"
  );
  cookieConsentBannerElement.availableCategories = [
    {
      description:
        "Enable you to navigate and use the basic functions and to store preferences.",
      key: "technically_required",
      label: "Technically necessary cookies",
      isMandatory: true,
    },
    {
      description:
        "Enable us to determine how visitors interact with our service in order to improve the user experience.",
      key: "analytics",
      label: "Analysis cookies",
    },
    {
      description:
        "Enable us to offer and evaluate relevant content and interest-based advertising.",
      key: "marketing",
      label: "Marketing cookies",
    },
  ];
</script>

<script>
  // =========================================================================
  // EXAMPLE
  // ANALYTICS w/o TAG MANAGER
  // =========================================================================
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    dataLayer.push(arguments);
  }
  gtag("js", new Date());

  gtag("config", "ENTERID");

  function loadAnalyticsScript() {
    // Add Script only once
    const scriptElementExists = document.querySelector("[data-scriptid='ga']");
    if (scriptElementExists || window?.ga) return;

    const firstScriptElement = document.getElementsByTagName("script")[0];

    const scriptElement = document.createElement("script");
    scriptElement.type = "text/javascript";
    scriptElement.setAttribute("async", "true");
    scriptElement.setAttribute(
      "src",
      "https://www.googletagmanager.com/gtag/js?id=ENTERID"
    );
    scriptElement.setAttribute("data-scriptid", "ga");

    firstScriptElement.parentNode.insertBefore(
      scriptElement,
      firstScriptElement
    );
  }
  // =========================================================================
  // COOKIE CONSENT: LOAD SCRIPTS AFTER USER INTERACTION
  // =========================================================================
  function loadScripts(event) {
    const acceptedCategories = event?.detail?.acceptedCategories;

    if (acceptedCategories.includes("analytics")) {
      console.log("Analytics accepted.");

      loadAnalyticsScript();
    }
    if (acceptedCategories.includes("marketing")) {
      console.log("Marketing accepted.");
    }
  }

  window.addEventListener("cookie_consent_preferences_restored", loadScripts);
  window.addEventListener("cookie_consent_preferences_updated", loadScripts);
</script>

Disclaimer

Please note that you must individually assess the legal requirements regarding the implementation of the Cookie Consent Banner, in particular which choices to offer in which granularity and which information to provide in which detail and at which point of the user journey. The examples mentioned are not intended to provide any advice regarding legal requirements. All responsibility for the implementation of the Cookie Consent Banner and its compliance with legal requirements lies with the user.

License

See LICENSE.

FAQs

Package last updated on 09 Oct 2023

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
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc