Language
Category
Search

uabiConsent v1.1: Cookie Management Linked with Analytics and Adsense

Simple and free JavaScript to manage cookies in compliance with GDPR, LGPD and others. Multilingual support, customizable banner, explicit and implicit consent using signals

Index

uabiConsent v1.1: Cookie Management Linked with Analytics and Adsense
At JavaScript By Rudi Drusian Lange
Published on
Last updated

Introduction

In recent years, the evolution of international standards for protecting people's privacy, such as the GDPR and the LGPD, has reinforced the need for companies and developers to adopt practices that ensure transparency, explicit consent, and respect for user rights.

Compliance with these regulations is not only a legal obligation but also a competitive advantage that strengthens public trust.

Tools that assist in managing cookie consent to ensure legal compliance have become indispensable. It was in this context that uabiConsent emerged, an open-source and completely free solution.

Developed in pure JavaScript, the solution eliminates the need for additional libraries, ensuring lightweight and simple implementation while offering high customization and support for multiple languages.

Download

To download uabiConsent, click the Download button or access the repository directly on GitHub:

Loading

Include the CSS and JavaScript in your site by adding the following code to your HTML:

HTML

<link rel='stylesheet' href='/path/to/css/uabi-consent-1.1.min.css'>
<script src='/path/to/js/uabi-consent-1.1.min.js'></script>

The best location for the CSS is inside the <head> tag of the HTML, while the JavaScript should be inserted just before the closing </body> tag.

Translations

The translation file uabi-consent-1.1.lang.json should be copied to the same directory as the main JavaScript file. This file contains translations available in English, Portuguese, and Spanish.

If necessary, translations can be modified directly in the JSON file. It is also possible to add support for new languages by following the existing structural pattern.

Initialization

After loading the main JavaScript, insert the following code to initialize uabiConsent:

JavaScript

myUabiConsent = new uabiConsent({
   name: 'uabiConsent-',
   lang: 'en',
   initialConsent: 'denied',
   expire: 365,
   privacyPolicyUrl: 'https://telazul.drusian.com.br/en/article/privacy-policy',
   showDecline: true,
   showSettings: true,
   consoleLog: true
});

Explanation:

  • name: The value set here will be used as a prefix for the names of different cookie types. For example, with the above configuration, the performance cookie will be stored as uabiConsent-performanceCookies. Modify as needed or use the default value.
  • lang: Sets the interface language. Supported languages: 'en' (English), 'pt' (Portuguese) and 'es' (Spanish).
  • initialConsent: Defines the initial consent before the user makes a choice:
    • 'granted': Cookies will be stored without explicit user consent.
    • 'denied': Cookies will only be stored after explicit user consent.
  • expire: Cookie expiration time in days.
  • privacyPolicyUrl: URL for the site's privacy policy. This option is mandatory for the script to function.
  • showDecline: Shows true or hides false the button to decline all cookies.
  • showSettings: Shows true or hides false the button to customize cookie types individually.
  • consoleLog: Displays the value set for each cookie type in the browser console. Useful for testing and debugging but recommended to disable in production.

Cookie Types

uabiConsent offers four customizable cookie types to meet site needs and ensure compliance with privacy regulations. Below are the details of each type:

  1. Strictly Necessary Cookies:
    • Essential for basic site functionality and cannot be disabled.
    • Typically created in response to user actions, such as setting privacy preferences, logging in, or filling out forms.
    • Do not store personally identifiable information.
  2. Performance Cookies:
    • Used to measure and improve user experience and site performance.
    • Collect data on visit counts, traffic sources, and how visitors interact with the site (e.g., most visited pages).
    • Tools like Google Analytics fall into this category.
    • All information collected is aggregated and anonymous.
  3. Functional Cookies:
    • Provide enhanced functionality and personalization on the site.
    • May be set by the site itself or by third parties.
    • Examples include remembering user preferences like theme, language, or region.
  4. Targeting Cookies:
    • Used to make advertisements more relevant to the user's interests.
    • May be set by the site or by third parties, such as Google Adsense.
    • When accepted, they allow personalized ads based on user preferences.
    • When declined, ads will be displayed without personalization.

Reference

This cookie classification system and the texts used on this page and in the script were inspired by the cookie management system available on Stack Overflow.

Important Note

When the script is configured to consider initial consent as 'denied', the behavior of integrated tools follows these rules:

  • Google Analytics will load with signals to not store cookies.
  • Google Adsense will display ads without personalization based on user preferences.

By accepting or declining cookies using the corresponding buttons, the appropriate signals will be sent automatically to ensure Analytics and Adsense adjust their operations according to user preferences.

Changing Consent

After the user accepts, declines, or customizes cookie preferences, the dialog will close. To allow the user to reopen the dialog and adjust settings later, simply create a link with the class 'uabi-consent-show-dialog'.

Example:

Cookies

HTML

<a href='#' class='uabi-consent-show-dialog'>Cookies</a>

Clicking the link above will reopen the consent dialog, allowing the user to adjust cookie preferences.

Integrating with Google Analytics and Adsense

Below is an example of how to configure Google Analytics and Google Adsense to be loaded automatically by uabiConsent:

JavaScript

myUabiConsent = new uabiConsent({
   name: 'uabiConsent-',
   lang: 'en',
   initialConsent: 'denied',
   expire: 365,
   privacyPolicyUrl: 'https://telazul.drusian.com.br/en/article/privacy-policy',
   showDecline: true,
   showSettings: true,
   analytics: true,
   analyticsID: 'G-YOUR_ID',
   adsense: true,
   adsenseID: 'ca-pub-YOUR_ID'
});

How Adsense Ads Work

Google Adsense automatic ads will be displayed using only the initialization above. However, for manual ads, where you decide their placement on the site, you must include the <ins> element in the HTML code. Example:

HTML

<ins class='adsbygoogle'
     style='display:block'
     data-ad-client='CLIENT_ID'
     data-ad-slot='AD_SLOT'
     data-ad-format='auto'
     data-full-width-responsive='true'>
</ins>

Google Analytics is enabled/disabled in the settings under Performance Cookies, while Adsense is managed under Targeting Cookies.

No additional configuration is required for these tools to function. They are loaded automatically based on user preferences set in uabiConsent.

Important: Avoid Conflicts

If Google Analytics or Google Adsense is being loaded by another method (e.g., scripts directly inserted into the HTML), it must be removed to avoid conflicts with uabiConsent's integrated functionality.

Implicit Consent

Implicit consent occurs when the user is considered to have accepted the site's terms or conditions simply by browsing or using it, without the option to explicitly decline (opt-out). This practice is common in countries where privacy regulations do not yet require explicit consent for data collection or processing.

To ensure compliance with global standards and respect user privacy, it is recommended to always offer clear options and allow users to manage their preferences.

uabiConsent allows implicit consent configuration, as demonstrated below:

JavaScript

myUabiConsent = new uabiConsent({
   name: 'uabiConsent-',
   lang: 'en',
   initialConsent: 'granted',
   privacyPolicyUrl: 'https://telazul.drusian.com.br/en/article/privacy-policy',
   showDecline: false,
   showSettings: false
});
  • The option initialConsent: 'granted' sets consent to be granted automatically when the site loads.
  • The settings showDecline: false and showSettings: false disable the decline and customization buttons, respectively, implementing implicit consent.
  • The script will display a message informing users that by browsing the site, they accept the use of cookies according to the privacy policy, with a link for reference.

Combining initialConsent: 'granted' with showSettings: true ensures initial consent is granted automatically before the user interacts with the settings. However, when accessing the manual customization screen, all options will be enabled by default.

Important: In countries with stricter privacy laws, such as GDPR and LGPD, customization options should be disabled by default, allowing users to enable them manually.

Multiple Languages

uabiConsent supports multiple languages, allowing the script to be dynamically configured based on the site's language. Below, we demonstrate how to initialize it on a site using multiple languages based on the URL.

General Functionality

  1. Extracting Language from URL: The getSiteLang() function extracts the site's language from the browser's URL. This assumes the URL structure follows the format: https://domain.com/language/. For example:
    • https://domain.com/en/ →Language: English (en)
    • https://domain.com/pt/ →Language: Portuguese (pt)
    • https://domain.com/es/ →Language: Spanish (es)
  2. Setting the Privacy Policy: Based on the extracted language, the code defines the URL for the privacy policy, ensuring users access the correct version in their language.
  3. Script Initialization: The uabiConsent script is initialized with the appropriate settings, including the detected language and corresponding privacy policy URL.

JavaScript

// Function to extract language from URL
function getSiteLang() {
   const path = window.location.pathname;
   const array = path.split('/');
   return array[1];
}
const myUabiLang = getSiteLang();

// Privacy policy based on language
if (myUabiLang == 'en') {
   myUabiPrivacyPolicy = 'https://example.com/en/privacy-policy';
} else if (myUabiLang == 'pt') {
   myUabiPrivacyPolicy = 'https://telazul.drusian.com.br/pt/artigo/politica-de-privacidade';  
} else if (myUabiLang == 'es') {
   myUabiPrivacyPolicy = 'https://example.com/es/politica-de-privacidad';
}

// Initializing the script
myUabiConsent = new uabiConsent({
   name: 'uabiConsent-',     // Cookie prefix
   lang: myUabiLang,         // Detected language
   initialConsent: 'denied', // Initial consent denied
   privacyPolicyUrl: myUabiPrivacyPolicy // Privacy policy URL
});

Checking User Consent

For Google Analytics and Google Adsense, the script automatically sends signals corresponding to cookie acceptance or rejection, requiring no additional configuration.

However, to retrieve cookie consent values and set new cookies based on user choices, or to integrate the script with other tools, you must use the getCookie() function. This function checks the status of a specific cookie type and makes decisions based on user consent.

JavaScript

if (getCookie(myUabiConsent.opt.name + 'functionalCookies') === 'granted') {
   // Code to execute if the user consented to functional cookies
}

The condition above checks if the value of the 'functionalCookies' cookie is 'granted'. If true, the code inside the block will execute. To check other cookie types, replace 'functionalCookies' with: 'performanceCookies' or 'targetingCookies'.

For debugging and testing, you can initialize uabiConsent with the option consoleLog: true. This displays cookie consent values in the browser console, allowing you to validate their behavior. Remember to disable this option in production environments.

Features

uabiConsent provides a dialog to request user permission for storing cookies with different purposes. Below are its main features:

    1. Two Consent Types:
      • Explicit Consent: The user chooses whether and which cookies to consent to, offering granular control over preferences.
      • Implicit Consent: Informs the user that cookies will be stored automatically, making site usage conditional on consent.
    2. Privacy Policy:
      • Allows setting the site's privacy policy URL, ensuring legal compliance and transparency.
    3. Multilingual Support:
      • Supports three languages: English, Spanish, and Portuguese.
      • New languages can be added, expanding the script's global reach.
    4. Text Customization:
      • All dialog messages and button texts are customizable in all languages.
      • Uses different texts for the main message and consent button depending on whether consent is explicit or implicit. Both are fully configurable.
    5. Initial Settings:
      • Allows defining initial consent, i.e., whether consent is considered granted or denied before the user makes a choice.
    6. Button Control:
      • Configures whether the Decline Cookies and Customize Cookies buttons are displayed.
    7. Settings Link:
      • Facilitates creating a link to reopen the cookie settings dialog, allowing users to change preferences at any time.
    8. Console Logs:
      • Offers an option to log cookie values in the browser console, useful for debugging. Recommended to disable in production.
    9. Automatic Tool Integration:
      • Integrates automatically with Google Analytics and Google Adsense using signals. Simply provide the corresponding IDs, and the tools will load based on user choices.
    10. Visual Customization:
      • Allows complete dialog customization via the included SASS (.scss) file, enabling design adjustments to meet the site's visual needs.

Site Notes

This is not my original language and I don't speak it very well. I used my little knowledge and translators tools to compose the text of this article. Sorry for possible spelling or grammatical errors, suggestions for corrections are appreciated and can be sent to the contact email in the footer of the site. My intention is to share some knowledge and I hope this translation is good enough.


Some of the content on this website, including text, images, graphics and other materials, may be generated or enhanced by artificial intelligence (AI) tools. For more details on the use of AI, please see our Term of Use.

Advertisement
Index
Advertisement