Skip to content

alma-oss/cookie-consent-manager

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

npm version CI

Alma Career Cookie Consent Manager

Provide configurable cookie consent plugin for Alma Career (formerly LMC) products. The package contains predefined Alma Career settings, translations and UI based on Spirit Design System.

The package is a wrapper around Cookie Consent by Orest Bida.

Table of contents

  1. Upgrade to version 3.x
  2. Basic usage
  3. Loading the plugin
  4. Manage features depending on the given consent
  5. Configuration
  6. Configuration options
  7. Theming
  8. Development and contributing

Upgrade to version 3.0

See upgrade guide for upgrade guidance from version 2.x to version 3.0. For complete list of changes see changelog.

Basic usage

Make assets load faster by placing pre-connect headers right after <meta charset> in your <head>:

<link rel="preconnect" href="https://cdn.jsdelivr.net">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

Load default CSS along with your styles in <head>:

<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@almacareer/cookie-consent-manager@3/CookieConsentManager.min.css">

If you use an older version of Alma Career's Spirit Design System (version 2 or lower) or if you don't use the Spirit Design System at all, you need to load the themes CSS file:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@almacareer/cookie-consent-manager@3/CookieConsentManagerThemes.min.css">

Load the script and initialize the plugin right before ending </body> tag:

<script defer src="https://cdn.jsdelivr.net/npm/@almacareer/cookie-consent-manager@3/init.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function () {
  initCookieConsentManager('demo.example'); // use the name of your service, like jobs.cz, seduo.pl etc.
});
</script>

This will load the plugin from CDN and initialize the plugin with default settings.

As a next step, add a link to open cookie preferences after the consent was previously given. This link should be placed somewhere in the page footer, usually near "Terms of use" and "Privacy policy" links. Please note it is legally required to provide the user such link to change cookie preferences even after the first consent is given.

<a href="" data-cc="show-preferencesModal">Open cookie preferences</a>

πŸ‘€ See demo page with example.

Loading the plugin

Via CDN or static file

You can load the plugin from a CDN, as in the basic example above.

<!-- Note we use version "cookie-consent-manager@3", which points to the latest version of this series (including feature and bugfix releases) -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@almacareer/cookie-consent-manager@3/CookieConsentManager.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@almacareer/cookie-consent-manager@3/CookieConsentManagerThemes.min.css"><!-- Only if you do NOT use Spirit Design System (or you use Spirit Design System version 2 or lower) -->
<script defer src="https://cdn.jsdelivr.net/npm/@almacareer/cookie-consent-manager@3/init.js"></script>

Alternatively, you can also download the latest version from the Releases page.

Loading the plugin from CDN or static file is recommended mostly for static sites without their own build process.

Once the plugin is loaded, you need to initialize it using initCookieConsentManager() method, optionally providing configuration parameters.

Via npm

For projects with their own build process for JavaScript, it is recommended to use the plugin via npm package @almacareer/cookie-consent-manager.

  1. Add the plugin to your dependencies:

    yarn add @almacareer/cookie-consent-manager

    or

    npm install --save @almacareer/cookie-consent-manager
  2. Import the module in your javascript:

    import CookieConsentManager from '@almacareer/cookie-consent-manager';
    
    window.addEventListener('DOMContentLoaded', function () {
      CookieConsentManager('demo.example'/* , optional plugin configuration */);
    });

    See below for configuration options.

    You can also look at the example with EcmaScript module syntax.

  3. Include default CSS in your HTML:

    <link rel="stylesheet" href="node_modules/@almacareer/cookie-consent-manager/CookieConsentManager.min.css">
    <link rel="stylesheet" href="node_modules/@almacareer/cookie-consent-manager/CookieConsentManagerThemes.min.css"><!-- Only if you do NOT use Spirit Design System (or you use Spirit Design System version 2 or lower) -->

    or in your Sass stylesheet:

    @use "node_modules/@almacareer/cookie-consent-manager/CookieConsentManager.css";
    @use "node_modules/@almacareer/cookie-consent-manager/CookieConsentManagerThemes.css"; // Only if you do NOT use Spirit Design System (or you use Spirit Design System version 2 or lower)

    Please mind the .css extension used in the Sass example. Using the provided .scss stylesheet is recommended only for projects that are built with Alma Career's Spirit Design System.

    Also, the themes CSS is optional and should be included only if you do NOT use Alma Career's Spirit Design System (or you use Spirit Design System version 2 or lower). For projects built with Spirit Design System version 3 and newer, the themes are already included in the CSS.

    See below for theme customization options.

  4. For projects that are NOT built with Alma Career's Spirit Design System or use Spirit Design System version 2 or lower:

    1. Include default font in your HTML:

      <link rel="preconnect" href="https://fonts.googleapis.com">
      <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap">

      or in your Sass stylesheet:

      @import url("https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap");
    2. Or switch to custom font that matches the design of your project.

Manage features depending on the given consent

For cookies within "necessary" category it is not needed to check whether a user has given any consent.

However, for all other purposes, it must be explicitly checked whether user has given the appropriate consent category. This must be done before the respective cookie is set.

In case user rejects some (or all) optional consent categories, you must implement logic to remove current cookies (as well as localStorage) in your product yourself, this library does not manipulate with the cookies by default. (However you can use autoClearCookies config option.)

Consent categories

Category Description
necessary Strictly necessary cookies are essential for user to browse the website and use its features, such as accessing secure areas of the site. These cookies are first-party cookies.
Some examples of strictly necessary cookies: Session cookies, Cookie consent cookies, Load balancing cookies, CSFR tokens, Language selection cookies, Region/country cookies, Performance cookies, Application firewall cookies and JavaScript check cookies.
For these cookies you don't need to check whether user actually has this category.
ad For cookies related to advertising
analytics For analysis and statistics
functionality For extended functionality (not covered by necessary category)
personalization For personalization based on user profiling (recommendation, etc.)

GTM (Google Tag Manager) scripts

If you manage GTM script outside of Alma Career Central, you must set proper GTM consent mode properties to dataLayer. See this example (or you can use onFirstConsent() and onChange() callbacks).

If GTM of the product is managed by Alma Career Central, after implementing this library, you don't need to worry about conditions when to run them. However, keep in mind you still need to take care (i.e. delete) of already existing cookies, even of those created by GTM scripts.

Custom methods

To execute custom code which depends on cookie consent use callbacks:

// ...
initCookieConsentManager(
  'demo.example',
  {
    onConsent: ({ cookieConsent, cookie }) => {
      if (cookieConsent.acceptedCategory('functionality')) {
        startOptionalFeature();
      }
    },
  }
);
// ...

Third party scripts loaded via <script>

To automatically load external scripts after a specific consent category is given by the user, modify the <script> tag: set type to type="text/plain" and add data-category attribute with required consent category.

<script src="personalization.js" type="text/plain" data-category="personalization" defer></script>

<script type="text/plain" data-category="functionality">
   console.log('functionality consent given');
</script>

πŸ‘€ This feature is also shown in examples. See also full documentation for this feature.

This feature is enabled by default. If you'd like to disable it, you can do so by overriding manageScriptTags value in config option:

initCookieConsentManager(
  'demo.example',
  {
    config: {
      manageScriptTags: false
    }
  }
);

Configuration

Optional config parameters could be provided on plugin initialization as the second parameter, encapsulated in the configuration object.

initCookieConsentManager( // when loaded as a module, these options are passed to `CookieConsentManager()` instead
  'demo.example', // provide the name of your service, like jobs.cz, seduo.pl etc.
  {
    defaultLang: 'cs',
    autodetectLang: false,
    onConsent: ({ cookieConsent, cookie }) => {
      // custom code
    },
    translationOverrides: { // overrides of the default translation for specified languages
      cs: { consentTitle: 'VlastnΓ­ nadpis', descriptionIntro: 'VlastnΓ­ ΓΊvodnΓ­ text popisu souhlasu' },
      en: { consentTitle: 'Custom title' },
    },
    cookieTable: { // cookie table for specified languages, shown in preferences modal
      cs: {
        necessary: [
          { name: 'almacareer_ccm', description: 'Cookie je nezbytnΓ‘ k uloΕΎenΓ­ vaΕ‘ich preference tΓ½kajΓ­cΓ­ se povolenΓ½ch kategoriΓ­ cookies', expiration: '1 rok' },
          { name: 'PHPSESSID', description: 'Cookie nezbytnΓ‘ ke sprΓ‘vnΓ©mu fungovΓ‘nΓ­ webu', expiration: 'do konce relace' },
        ],
        // ad: [ ... ],
        analytics: [
          { name: '_ga', description: 'NΓ‘strojem Google Analytics zjiΕ‘Ε₯ujeme, kolik lidΓ­ nΓ‘Ε‘ web navΕ‘tΔ›vuje a jak ho pouΕΎΓ­vΓ‘', expiration: '2 roky' },
          { name: '_utm', description: 'NΓ‘strojem Google Analytics zjiΕ‘Ε₯ujeme, kolik lidΓ­ nΓ‘Ε‘ web navΕ‘tΔ›vuje a jak ho pouΕΎΓ­vΓ‘', expiration: '2 roky' },
        ],
        // functionality: [ ... ],
        // personalization: [ ... ]
      },
      en: {
        analytics: [
          { name: '_ga', description: 'With Google Analytics we determine how many people visit our website and how they use it', expiration: '2 years' },
          // ...
        ],
      }
    },
    config: {
      // overrides of the internal config of the underlying library, see https://cookieconsent.orestbida.com/reference/configuration-reference.html
    },
  }
);

πŸ‘€ See extended configuration example

Configuration options

Option Type Default value Description
autodetectLang boolean true Autodetect language based on the value of <html lang="...">. If autodetect fails or if unsupported language is detected, fallback to defaultLang.
When disabled, force language to defaultLang.
defaultLang string 'cs' Default language. One of cs, de, en, hu, pl, ru, sk, uk. This language will be used when autodetect is disabled or when it fails.
companyNames array ['Alma Career'] Array of strings with company names. Adjust only when the consent needs to be given to multiple companies. Value "Alma Career" is replaced with translated legal name. See example.
consentCollectorApiUrl ?string 'https://consents.almacareer.tech/acl-lda/(...)' URL of the API where user consent information is sent. Null to disable sending data to the API.
config Object {} Override internal config of the underlying library. For all parameters see config reference of the original library.
displayMode DisplayMode (string) DisplayMode.FORCE (force) force (default) to show consent in a centered modal box and to block page until user action. soft to show consent banner on the bottom of the page and do not block the page before user action.
on* callbacks function (cookieConsent) => {} See below for configurable callbacks.
translationOverrides Record<string, TranslationOverride> {} Override default translation for specified languages. consentTitle, descriptionIntro and preferencesModalMoreInfo could be overridden.
See example
cookieTable CookieTable {} Define a cookie table (shown in the preferences modal) for specified languages and specified categories.
See above for example configuration

Supported languages

Translation of the user interface is provided in the following languages:

  • Bosnian (bs)
  • Croatian (hr)
  • Czech (cs)
  • English (en)
  • Estonian (et)
  • French (fr)
  • German (de)
  • Hungarian (hu)
  • Latvian (lv)
  • Lithuanian (lt)
  • Macedonian (mk)
  • Polish (pl)
  • Portuguese (pt)
  • Romanian (ro)
  • Russian (ru)
  • Serbian (latin) (sr)
  • Slovak (sk)
  • Slovenian (sl)
  • Spanish (es)
  • Ukrainian (uk)

πŸ‘€ See example of each language version

Callbacks

The library can trigger configured callbacks in various events. They can be used to execute custom functionality, for example, to enable some feature after user has given consent.

Each configured callback receives cookieConsent as part of the options object. This is instance of the underlying cookie consent library, that can be used to call its methods or retrieve data from the cookie. cookie parameter contains value of the consent cookie. onChange() callback also receiver categories object, containing array of accepted, rejected, and changed consent categories.

Callback Trigger event
onFirstConsent({ cookieConsent, cookie }) This function will be executed only once, when the user takes the first action (accept all/only selected/only necessary categories).
onConsent({ cookieConsent, cookie }) Any consent is detected (either given now or after page load if it was already saved previously)
onChange({ cookieConsent, cookie, categories }) Right after the user changes cookie preferences. The callback receives also categories object containing arrays of accepted, rejected, and changed categories.

πŸ‘€ See callbacks example

Theming

With Spirit Design System

If your project uses Spirit Design System version 3 and newer, you are almost done!

All you need to do is to add this plugin's SCSS to your Sass pipeline and use it instead of the default CSS:

// my-project.scss

// Add this line anywhere you import other third-party CSS, possibly somewhere close
// to the end of your stylesheet as it contains CSS selectors with high specificity.
@use '@almacareer/cookie-consent-manager/CookieConsentManager';

That's it!

Make sure you have node_modules and path to your design tokens in your Sass load paths.

Set up Sass load path so the Sass compiler can find stylesheets located in the node_modules directory (you will already have a path to your design tokens there, as required by Spirit Web):

# CLI command (possibly used in your npm scripts)

sass --load-path=node_modules --load-path=path/to/my/design-tokens my-project.scss my-project.css

Or with webpack:

// webpack.config.js

{
  loader: 'sass-loader',
  options: {
    sassOptions: {
      loadPaths: [
        path.resolve(
          __dirname,
          'node_modules',
          'path/to/my/design-tokens',
        ),
      ],
    },
  },
},

Note: sass v1.23 or higher is required to be able to compile the new Sass modules syntax. You may need to migrate to sass since all other Sass compilers (and the old @import rule) are now deprecated.

With Spirit Design System version 2 or lower

Please follow the steps below for users who do not use Spirit Design System.

Without Spirit Design System

A handful of CSS custom properties are available for you to customize the UI to make it match the design of your site. For example, to change the text color of cookie consent UI, load the default CSS and add the following code anywhere in your stylesheet (the order of which is not important):

:root {
  --cc-primary-color: #333;
}

πŸ‘€ See theming example

Full list of available CSS custom properties:
Category CSS custom property Description
Common --cc-font-family Base font family
--cc-bg Common background color
--cc-primary-color Common primary text color
--cc-secondary-color Common secondary text color
Links --cc-link-color Link text color
Buttons --cc-btn-border-radius Button border radius
--cc-btn-primary-bg Primary button background color
--cc-btn-primary-color Primary button text color
--cc-btn-primary-border-color Primary button border color
--cc-btn-primary-hover-bg Primary button background color on hover
--cc-btn-primary-hover-color Primary button text color on hover
--cc-btn-primary-hover-border-color Primary button border color on hover
--cc-btn-secondary-bg Secondary button background color
--cc-btn-secondary-color Secondary button text color
--cc-btn-secondary-border-color Secondary button border color
--cc-btn-secondary-hover-bg Secondary button background color on hover
--cc-btn-secondary-hover-color Secondary button text color on hover
--cc-btn-secondary-hover-border-color Secondary button border color on hover
Toggles --cc-pm-toggle-border-radius Toggle border radius
--cc-toggle-on-bg Toggle background color in selected state
--cc-toggle-off-bg Toggle background color in unselected state
--cc-toggle-on-knob-bg Toggle knob color in selected state
--cc-toggle-off-knob-bg Toggle knob color in unselected state
--cc-toggle-readonly-bg Toggle background color in readonly state
--cc-toggle-readonly-knob-bg Toggle knob color in readonly state
--cc-toggle-readonly-knob-icon-color Toggle knob icon color in readonly state
Cookie categories --cc-cookie-category-block-bg Cookie category block background color
--cc-cookie-category-block-border Cookie category block border color
--cc-cookie-category-block-hover-bg Cookie category block background color on hover
--cc-cookie-category-block-hover-border Cookie category block border color on hover
--cc-cookie-category-expanded-block-bg Expanded cookie category block background color
--cc-cookie-category-expanded-block-hover-bg Expanded cookie category block background color on hover
Separators --cc-separator-border-color Separator border color
Backdrop --cc-overlay-bg Backdrop background color
Modal --cc-modal-margin Modal margin
--cc-modal-border-radius Modal border radius
--cc-modal-transition-duration Modal transition duration
Footer --cc-footer-bg Footer background color
--cc-footer-color Footer text color
--cc-footer-border-color Footer border color

Color themes

Starting from version 3, the Cookie Consent Manager supports color themes.

Spirit color themes

The themes are based on the Spirit Design Tokens, version 3.

For Spirit Design System users, the themes are already included in the CSS.

For projects that are NOT built with Spirit Design System (or use Spirit Design System version 2 or lower), you need to load the themes CSS file first.

Having the themes loaded, you can switch between the modes by applying the CSS classes like .theme-light-default or .theme-light-on-brand to any element of your application.

Dark mode

While the Spirit Design System does not yet provide a dark mode, you can easily create one by overriding the CSS custom properties:

@media (prefers-color-scheme: dark) {
  :root {
    --cc-bg: #333;
    --cc-primary-color: #fff;
    --cc-secondary-color: #ccc;
    /* … */
  }
}

Custom font

Default cookie consent design uses Inter font loaded via Google Fonts as shown in the basic example. If you are not using cookie consent with the default design, additional steps may be necessary for you:

  • If your project is built with Spirit Design System, you already have the correct font linked in your HTML or CSS.
  • If your project is not built with Spirit Design System, you can switch to any font of your choice:
    :root {
      --cc-font-family: "Open Sans", arial, sans-serif;
    }

If you use a custom font like this, make sure you don't load the default Inter font and that you use <link rel="preconnect" ...> only to actually needed domains.

Development and contributing

Local development

Install package dependencies:

yarn install

Start local development server:

yarn start

This will make the development server accessible http://localhost:5173/ .

Contributing

For commit messages follow Conventional Commits specification with Alma Career rules. The commit message will also be automatically checked as pre-commit hook.

To ensure the code passes linting and code style test run:

yarn test

To fix code style according to Prettier rules run:

yarn format:fix

Publishing package

Prepare release using yarn release on a local machine. Check the generated changelog and the bumped package.json. Then push to origin. GitHub publish action is then taking care of publishing package to npmjs.com.

License

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