tarteaucitron.js

repository·master·Indexed 21 days ago

https://github.com/amauric/tarteaucitron.js

A GDPR-friendly cookie management script (version 1.34.0) that provides a compliant and accessible cookie banner and control panel. It handles user consent for third-party services, manages cookie storage, and supports integrations with Google Consent Mode v2, Bing Consent Mode, and Piano Analytics. The library allows for custom service definitions, translation overrides, and provides a comprehensive set of document and window events to react to consent changes.

Tokens
6.1K
Snippets
17
Records
23
Agent score
27%

What's inside tarteaucitron.js

  1. Initialize tarteaucitron.js

    master

    To use tarteaucitron.js, include the script in your HTML and call tarteaucitron.init() with a configuration object. The script manages GDPR compliance by disabling services by default, displaying a consent banner, and storing consent in a cookie for 365 days.

    <script src="/tarteaucitron/tarteaucitron.js"></script>
    
    <script>
    tarteaucitron.init({
        "privacyUrl": "", /* Privacy policy url */
        "bodyPosition": "bottom", /* or top to bring it as first element for accessibility */
        "hashtag": "#tarteaucitron", /* Open the panel with this hashtag */
        "cookieName": "tarteaucitron", /* Cookie name */
        "orientation": "middle", /* Banner position (top - bottom - middle - popup) */
        "groupServices": false, /* Group services by category */
        "showDetailsOnClick": true, /* Click to expand the description */
        "serviceDefaultState": "wait", /* Default state (true - wait - false) */
        "showAlertSmall": false, /* Show the small banner on bottom right */
        "showTitleBanner": false, /* Also show the title (middleBarHead) on the top/bottom banners */
        "cookieslist": false, /* Show the cookie list in a mini banner */
        "cookieslistEmbed": false, /* Show the cookie list on the control panel */
        "showIcon": true, /* Show cookie icon to manage cookies */
        "iconPosition": "BottomRight", /* Position of the icon between BottomRight, BottomLeft, TopRight and TopLeft */
        "adblocker": false, /* Show a Warning if an adblocker is detected */
        "DenyAllCta" : true, /* Show the deny all button */
        "AcceptAllCta" : true, /* Show the accept all button when highPrivacy on */
        "highPrivacy": true, /* HIGHLY RECOMMANDED Disable auto consent */
        "alwaysNeedConsent": false, /* Ask the consent for "Privacy by design" services */
        "handleBrowserDNTRequest": false, /* If Do Not Track == 1, disallow all */
        "removeCredit": false, /* Remove credit link */
        "moreInfoLink": true, /* Show more info link */
        "useExternalCss": false, /* If false, the tarteaucitron.css file will be loaded */
        "useExternalJs": false, /* If false, the tarteaucitron.services.js file and lang files will be loaded */
        "readmoreLink": "", /* Change the default readmore link pointing to tarteaucitron.io */
        "mandatory": true, /* Show a message about mandatory cookies */
        "mandatoryCta": true, /* Show the disabled accept button when mandatory on */
        "googleConsentMode": true, /* Enable Google Consent Mode v2 for Google ads and GA4 */
        "bingConsentMode": true, /* Enable Bing Consent Mode for Clarity and Bing Ads */
        "pianoConsentMode": true, /* Enable Piano Analytics Consent Mode */
        "pianoConsentModeEssential": false, /* Load in Essential mode instead of opt-out by default */
        "softConsentMode": false, /* Soft consent mode (consent is required to load the services) */
        "dataLayer": false, /* Send an event to dataLayer with the services status */
        "serverSide": false, /* Server side only, tags are not loaded client side */
        "partnersList": false /* Details the number of partners on the popup and middle banner */
    });
    </script>
  2. Configure service default states

    master

    When adding services, the default state (e.g., 'wait', 'true', or 'false') can be controlled in two ways:

    1. Per Service: Define service.defaultState within the service object itself.
    2. Globally: Set tarteaucitron.parameters.serviceDefaultState in the main configuration object.

    If neither is set, the service defaults to 'wait'.

  3. Enable Google Consent Mode and Data Layer integration

    master

    Tarteaucitron can automatically manage Google Consent Mode (GCM) and push consent updates to the Google Data Layer.

    To enable Data Layer updates, set dataLayer: true in your configuration. When consent is updated, an event tac_consent_update is pushed to the window.dataLayer containing the list of authorized vendors.

    When googleConsentMode is enabled (default), the library sets default consent states to denied and updates them to granted based on user interaction or service loading events.

    tarteaucitron.init({
        dataLayer: true,
        googleConsentMode: true
    });
  4. How consent state and service loading work

    master

    Tarteaucitron.js manages services through a lifecycle driven by user consent. When a service is triggered (either via init() or a manual response):

    1. Consent Check: The library checks if the service is allowed or if it's a 'safe' analytics service.
    2. Cookie Creation: If allowed, a cookie is created to persist the choice.
    3. Execution: If the service is allowed and hasn't been launched yet, the library executes the service's js() function (the script loader).
    4. Fallback: If consent is denied, the library executes the service's fallback() function (if provided), allowing you to run a privacy-friendly version of the service.
    5. UI Update: The UI is updated to reflect the new state (colors, progress bars, and status text).
  5. Customize translation text

    master

    To override default translations, define a tarteaucitronCustomText object before calling tarteaucitron.init(). This object is merged with the default translations.

    For service-specific engagement text (e.g., changing "X is disabled"), use the key format engage-{SERVICE_KEY}.

    tarteaucitronCustomText = {
      'support': {
        'title': 'Support client',
      },
      'close': 'Enregistrer et fermer',
      'engage-twitter': 'Follow us on Twitter!'
    };
    tarteaucitron.init(...);
  6. Listen to tarteaucitron.js events

    master

    The library emits several events that you can listen for on the document or window objects to react to consent changes or UI interactions.

    Document Events

    Triggered for each enabled service (replace {SERVICE_KEY} with the actual service key):

    • {SERVICE_KEY}_added: Service has been added.
    • {SERVICE_KEY}_loaded: Service has been loaded.
    • {SERVICE_KEY}_allowed: Service was allowed by the user.
    • {SERVICE_KEY}_disallowed: Service was disallowed by the user.

    Window Events

    • tac.root_available: The root element with the panel has been created and services will be loaded.
    • tac.open_alert: Triggered when an alert is opened.
    • tac.close_alert: Triggered when an alert is closed.
    • tac.open_panel: Triggered when the control panel is opened.
    • tac.close_panel: Triggered when the control panel is closed.
  7. Create a custom service

    master

    You can extend tarteaucitron.js by defining a new service object on the tarteaucitron.services namespace. This allows you to manage custom third-party scripts, their cookies, and their loading logic based on user consent.

    tarteaucitron.services.mycustomservice = {
      "key": "mycustomservice",
      "type": "ads|analytic|api|comment|other|social|support|video",
      "name": "MyCustomService",
      "needConsent": true,
      "cookies": ['cookie', 'cookie2'],
      "readmoreLink": "/custom_read_more", // If you want to change readmore link
      "js": function () {
        "use strict";
        // When user allow cookie
      },
      "fallback": function () {
        "use strict";
        // when use deny cookie
      }
    };
  8. Configure tarteaucitron via init() parameters

    master

    The init() method accepts a params object to configure the behavior of the consent manager. Below are the default parameters available in the current version:

    ParameterDefaultDescription
    adblockerfalseEnables adblocker detection
    hashtag'#tarteaucitron'The URL hash used to open the panel
    cookieName'tarteaucitron'The name of the cookie used to store consent
    highPrivacytrueIf true, services are blocked by default
    orientation'middle'Position of the bar ('top', 'middle', or 'bottom')
    bodyPosition'bottom'Position of the bar on the body
    removeCreditfalseWhether to hide the tarteaucitron link
    showAlertSmallfalseWhether to show a small alert instead of a large one
    showTitleBannerfalseWhether to show the title banner
    showDetailsOnClicktrueWhether to show service details when clicking a category
    showIcontrueWhether to show the icon
    iconPosition'BottomRight'Position of the icon
    cookieslistfalseWhether to show the cookies list
    cookieslistEmbedfalseWhether to embed the cookies list
    handleBrowserDNTRequestfalseWhether to respect the browser's Do Not Track request
    DenyAllCtatrueWhether to show a 'Deny All' button
    AcceptAllCtatrueWhether to show an 'Accept All' button
    moreInfoLinktrueWhether to show the more info link
    privacyUrl''URL to the privacy policy
    useExternalCssfalseWhether to use an external CSS file
    useExternalJsfalseWhether to use an external JS file
    mandatorytrueWhether some services are mandatory
    mandatoryCtatrueWhether mandatory services have CTA buttons
    closePopupfalseWhether to close the popup on interaction
    groupServicesfalseWhether to group services by category
    serviceDefaultState'wait'The default state for services
    googleConsentModetrueEnable Google Consent Mode
    pianoConsentModetrueEnable Piano Consent Mode
    pianoConsentModeEssentialfalsePiano mode: use essential only
    bingConsentModetrueEnable Bing Consent Mode
    softConsentModefalseIf false, services are unblocked only after consent
    dataLayerfalseWhether to push events to the Google Data Layer
    serverSidefalseWhether it is running on the server side
    partnersListfalseWhether to show the partners list
    alwaysNeedConsentfalseWhether consent is always required
  9. Configure Piano and Bing Consent Modes

    master

    Tarteaucitron supports integration with Piano Analytics and Bing/Clarity consent modes.

    Set pianoConsentMode: true. If pianoConsentModeEssential is also true, it sets the default preset to essential. Otherwise, it defaults to opt-out.

    Set bingConsentMode: true. This will initialize window.uetq and window.clarity with default 'denied' states and update them to 'granted' or 'denied' based on user consent.

  10. Initialize tarteaucitron with init()

    master

    To start the cookie consent manager, call tarteaucitron.init(params) where params is a configuration object. This method sets up event listeners (scroll, resize, keydown, etc.), loads the necessary CSS and language files, and prepares the user interface.

    Note that tarteaucitron.init() can only be called once per page load. If you need to trigger logic after initialization, use the events object to hook into the init or load lifecycle stages.

    tarteaucitron.init({
        // your configuration options here
        privacyUrl: 'https://example.com/privacy',
        // ...
    });
  11. Generate engagement UI with engage()

    master

    The tarteaucitron.engage(id) method generates the HTML for an 'engagement' element (a floating button or banner) that asks the user for consent for a specific service. This is useful for 'soft' opt-ins where you want to prompt the user to enable a service they haven't consented to yet.

    It uses the service's name and localized fallback text to create a button with the class tarteaucitronAllow.

    // Returns an HTML string for a service with ID 'google_analytics'
    const engagementHtml = tarteaucitron.engage('google_analytics');
    document.body.innerHTML += engagementHtml;
  12. Load scripts dynamically with addScript

    master

    Use tarteaucitron.addScript to inject scripts into the document. This is used to ensure third-party scripts are only loaded after consent is given.

    Parameters:

    • url (string): The source URL of the script.
    • id (string): The ID to assign to the script element.
    • callback (function): Function to execute once the script has loaded.
    • execute (boolean): If false, the callback is executed immediately without loading the script.
    • attrName (string): Optional attribute name to set on the script.
    • attrVal (string): Optional attribute value to set.
    • internal (boolean): If true, bypasses tarteaucitron.parameters.useExternalJs checks.
    tarteaucitron.addScript('https://example.com/script.js', 'my-script', function() {
        console.log('Script loaded and ready!');
    });