El banner no aparece

Problema

  • El banner de cookies no se muestra al cargar la página.
  • Los usuarios no ven la solicitud de consentimiento.

Pasos de diagnóstico

Paso 1: Comprueba si TermsFeed Cookie Consent está cargado

// Open browser console and type:
console.log(typeof cookieconsent);

// Should output: "object"
// If "undefined", script didn't load

Paso 2: Comprueba si hay errores de JavaScript

  1. Abre DevTools (F12)
  2. Ve a la pestaña Consola
  3. Busca errores

Entre los errores más comunes se incluyen:

  1. cookieconsent is not defined
  2. Uncaught ReferenceError
  3. Failed to load resource

Paso 3: Verifica la ubicación del script de consentimiento de cookies de TermsFeed

<!-- ❌ WRONG - Script in <head> without async -->
<head>
    <script src="//www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js"></script>
    <script>
        cookieconsent.run({ / config / });
    </script>
</head>

<!-- ✅ CORRECT - Script before </body> with DOMContentLoaded -->
<body>
    <!-- content -->

    <script src="//www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            cookieconsent.run({ / config / });
        });
    </script>
</body>

Causas y soluciones comunes

Causa 1: El usuario ya ha dado su consentimiento

// Check if user has cookie
console.log(document.cookie);
// Look for: cookie_consent_level=...

// To test banner, clear cookie:
document.cookie = 'cookie_consent_level=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
// Then reload page

Causa 2: Un bloqueador de anuncios está bloqueando TermsFeed Cookie Consent

La solución es integrar un servidor proxy para servir TermsFeed Cookie Consent.

Causa 3: La Política de seguridad de contenido (CSP) bloquea la carga

El error en Herramientas de desarrollador > Consola podría ser Refused to load the script ... violates the following Content Security Policy directive

La solución es actualizar los encabezados CSP:

Content-Security-Policy: script-src 'self' www.termsfeed.com 'unsafe-inline'

Causa 4: Configuración incorrecta

Errores comunes en la configuración:


// 1. Missing quotes
cookieconsent.run({
    consent_type: express  // ❌ Missing quotes
});

// 2. Trailing comma (IE issue)
cookieconsent.run({
    "consent_type": "express",  // ❌ Trailing comma
});

// 3. Missing DOMContentLoaded
cookieconsent.run({ / config / });  // ❌ Runs before DOM ready

// ✅ CORRECT:
document.addEventListener('DOMContentLoaded', function () {
    cookieconsent.run({
        "consent_type": "express",
        "website_name": "My Site",
        "language": "en"
    });
});

Causa 5: Scripts en conflicto

Es posible que otro script impida que se muestre el banner de consentimiento de cookies de TermsFeed.

La solución es comprobar el orden de carga de los scripts.

// Test isolation
// Temporarily remove ALL other scripts
// Keep ONLY cookie consent
// If banner shows, you have a conflict

// Common conflicts:
// - Other cookie consent tools
// - Privacy plugins
// - Ad blockers (client-side)

Modo de depuración

Habilitar el registro de depuración:

cookieconsent.run({
    "consent_type": "express",
    "website_name": "My Site",
    "debug": true  // Enable debug logging
});

// Check console for debug messages:
// [CookieConsent] Banner initialized
// [CookieConsent] User has no consent
// [CookieConsent] Showing banner

Los scripts no están siendo bloqueados

Problema

«He etiquetado mi script de Google Analytics con data-cookie-consent='tracking', ¡pero sigue activándose antes de que el usuario acepte las cookies!»

Pasos de diagnóstico

Paso 1: Verifica el etiquetado del script

<!-- ❌ WRONG -->
<script type="text/javascript" data-cookie-consent="tracking">
  // GA code
</script>

<!-- ✅ CORRECT -->
<script type="text/plain" data-cookie-consent="tracking">
  // GA code
</script>

<!-- Key difference: type="text/plain" NOT type="text/javascript" -->

Paso 2: Comprueba la pestaña Red

  1. Abre DevTools → pestaña Red
  2. Borra las cookies
  3. Recarga la página (antes de aceptar)
  4. Filtra tus scripts de seguimiento
  5. Los scripts etiquetados NO deberían aparecer en la pestaña Red

Paso 3: Comprueba si se están estableciendo cookies

  1. DevTools → Aplicación → Cookies
  2. Antes de aceptar: No hay cookies de Google Analytics
  3. Después de aceptar: aparecen las cookies _ga y _gid

Causas comunes y soluciones

Causa 1: El script se ha cargado antes del consentimiento de cookies

<!-- ❌ WRONG ORDER -->
<script type="text/plain" data-cookie-consent="tracking">
  // GA code
</script>
<script src="//www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js"></script>

<!-- ✅ CORRECT ORDER -->
<script src="//www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    cookieconsent.run({ / config / });
});
</script>

<!-- NOW tag scripts below -->
<script type="text/plain" data-cookie-consent="tracking">
  // GA code
</script>

Causa 2: El script externo no está bloqueado

<!-- ❌ External scripts need different approach -->
<script src="https://www.googletagmanager.com/gtag/js?id=G-XXX" data-cookie-consent="tracking"></script>

<!-- ✅ CORRECT - wrap in type="text/plain" -->
<script type="text/plain" data-cookie-consent="tracking">
  var script = document.createElement('script');
  script.src = 'https://www.googletagmanager.com/gtag/js?id=G-XXX';
  script.async = true;
  document.head.appendChild(script);

  script.onload = function() {
    // Initialize GA
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'G-XXX');
  };
</script>

Causa 3: Uso de Google Tag Manager

El problema habitual se produce cuando GTM se carga antes del consentimiento.

La solución es no etiquetar el propio contenedor de GTM. En su lugar:

  1. Cargar GTM normalmente (sin etiquetar)
  2. Configurar las etiquetas DENTRO de GTM para que se activen solo con el consentimiento
  3. Utilizar el modo de consentimiento integrado o activadores personalizados
<!-- Don't tag the GTM container -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var 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);
})(window,document,'script','dataLayer','GTM-XXXX');</script>

<!-- Instead, push consent state to dataLayer -->
<script>
document.addEventListener('DOMContentLoaded', function () {
    cookieconsent.run({
        // ... config ...
        "callbacks": {
            "scripts_specific_loaded": (level) => {
                // Push to dataLayer
                window.dataLayer = window.dataLayer || [];
                window.dataLayer.push({
                    'event': 'cookie_consent_update',
                    'consent_level': level
                });
            }
        }
    });
});
</script>

<!-- Then in GTM, create trigger:
   Event: cookie_consent_update
   Condition: consent_level equals tracking
-->

Causa 4: Las cookies son establecidas por el servidor

Si un servidor backend establece cookies antes de que se ejecute JavaScript, la solución es programar más lógica del lado del servidor.

<?php
// Check if user has consented (server-side)
$hasConsent = false;
if (isset($_COOKIE['cookie_consent_level'])) {
    $consentLevel = json_decode(urldecode($_COOKIE['cookie_consent_level']), true);
    $hasConsent = in_array('tracking', $consentLevel);
}

// Only set analytics cookies if user consented
if ($hasConsent) {
    setcookie('analytics_id', $user_id, time() + 86400, '/');
}
?>

El consentimiento no es persistente

Problema

«El usuario acepta las cookies, pero cuando navega a otra página o actualiza la página, ¡el banner vuelve a aparecer!»

Pasos de diagnóstico

Paso 1: Comprueba si se está estableciendo una cookie

// After accepting, open console and run:
console.log(document.cookie);

// Should see something like:
// cookie_consent_level=%5B%22strictly-necessary%22%2C%22tracking%22%5D

Paso 2: Comprueba las propiedades de la cookie

// DevTools → Application → Cookies
// Look for: cookie_consent_level

// Check:
// ✓ Domain: Should match your domain
// ✓ Path: Should be /
// ✓ Expires: Should be future date (1 year)
// ✓ HttpOnly: Should be unchecked (JavaScript needs access)
// ✓ Secure: Depends on your settings
// ✓ SameSite: Strict or Lax

Causas comunes y soluciones

Causa 1: Desajuste en la ruta de la cookie

Problema

Se ha establecido una cookie para /subdir, pero la página se encuentra en /

Solución

Asegúrate de que la cookie utilice la ruta raíz.

// Cookie should be set for path=/
// This happens automatically, but verify in DevTools

// If using cookie_domain parameter, DON'T include path:
cookieconsent.run({
    "cookie_domain": ".example.com",  // ✅ No path needed
    // Other config...
});

Causa 2: El navegador bloquea las cookies

Problema

La configuración de privacidad del navegador impide el almacenamiento de cookies.

Solución

El usuario debe ajustar la configuración del navegador.

// Detect if cookies are blocked
function areCookiesEnabled() {
    try {
        document.cookie = 'test=test; SameSite=Strict';
        const enabled = document.cookie.indexOf('test=') !== -1;
        document.cookie = 'test=; expires=Thu, 01 Jan 1970 00:00:00 UTC';
        return enabled;
    } catch (e) {
        return false;
    }
}

// Show warning if cookies disabled
if (!areCookiesEnabled()) {
    alert('Cookies are disabled in your browser. Please enable them to save your preferences.');
}

Causa 3: Eliminación de cookies conflictiva

Problema

Otro script o extensión del navegador elimina las cookies.

Solución

Comprueba qué está eliminando las cookies

// Check what's deleting cookies
// Add console log on page load:
console.log('Cookies on load:', document.cookie);

// If consent cookie is missing, something deleted it
// Common culprits:
// - Privacy extensions (Privacy Badger, uBlock)
// - Browser auto-delete (Firefox Enhanced Tracking Protection)
// - Another script calling document.cookie clear

Causa 4: Problemas con los subdominios

Problema

La cookie establecida en www.example.com no funciona en example.com

Solución

Utilice el parámetro cookie_domain.

cookieconsent.run({
    "cookie_domain": ".example.com",  // Note the leading dot!
    // This makes cookie valid for ALL subdomains
    // Other config...
});

Causa 5: Discrepancia entre HTTPS y HTTP

Problema:

La cookie se ha establecido con el indicador Secure en HTTPS, pero el sitio cambia a HTTP.

Solución:

Asegúrate de que el protocolo sea coherente O elimina el indicador de seguridad para realizar pruebas.

cookieconsent.run({
    "cookie_secure": false,  // Set to true ONLY if site is always HTTPS
    // Other config...
});

// For production HTTPS sites:
cookieconsent.run({
    "cookie_secure": true,  // ✅ Recommended for HTTPS
    // Other config...
});

El modo de consentimiento de Google no funciona

Problema

«He implementado el Modo de consentimiento de Google V2, pero Google Analytics sigue mostrando 0 eventos incluso cuando los usuarios aceptan las cookies».

Pasos de diagnóstico

Paso 1: Comprueba que la función gtag existe

// Open console:
console.log(typeof gtag);
// Should output: "function"

// If "undefined", gtag didn't load

Paso 2: Comprueba dataLayer

// Check dataLayer contents:
console.log(window.dataLayer);

// Should see consent events:
// [{event: "consent", ...}, {event: "config", ...}]

Paso 3: Utiliza Google Tag Assistant

  1. Instalación: Extensión de Chrome Tag Assistant
  2. Habilitar la depuración
  3. Actualizar la página
  4. Comprueba si hay eventos del modo de consentimiento

Causas comunes y soluciones

Causa 1: Orden de implementación incorrecto

<!-- ❌ WRONG ORDER -->
<script src="//www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js"></script>
<script>
gtag('consent', 'default', {'analytics_storage': 'denied'});
</script>

<!-- ✅ CORRECT ORDER -->
<!-- 1. Set default consent FIRST -->
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('consent', 'default', {
    'ad_storage': 'denied',
    'analytics_storage': 'denied'
});
</script>

<!-- 2. THEN load Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXX');
</script>

<!-- 3. THEN Cookie Consent -->
<script src="//www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    cookieconsent.run({
        // ... config with callbacks ...
    });
});
</script>

Causa 2: Falta el parámetro callbacks_force

// ❌ Without callbacks_force, callbacks won't fire for Consent Mode
cookieconsent.run({
    "callbacks": {
        "scripts_specific_loaded": (level) => {
            gtag('consent', 'update', {'analytics_storage': 'granted'});
        }
    }
    // Missing: "callbacks_force": true
});

// ✅ CORRECT
cookieconsent.run({
    "callbacks": {
        "scripts_specific_loaded": (level) => {
            gtag('consent', 'update', {'analytics_storage': 'granted'});
        }
    },
    "callbacks_force": true  // Required for Consent Mode!
});

Causa 3: Error tipográfico en los tipos de consentimiento

// ❌ Common typos:
gtag('consent', 'update', {
    'analytic_storage': 'granted'  // ❌ Missing 's'
});

gtag('consent', 'update', {
    'ad_store': 'granted'  // ❌ Should be 'ad_storage'
});

// ✅ CORRECT spellings:
gtag('consent', 'update', {
    'analytics_storage': 'granted',  // ✅
    'ad_storage': 'granted',         // ✅
    'ad_user_data': 'granted',       // ✅
    'ad_personalization': 'granted'  // ✅
});

Causa 4: Asignación de categorías incorrecta

// Make sure you're mapping correct categories
"callbacks": {
    "scripts_specific_loaded": (level) => {
        switch (level) {
            case 'tracking':  // ✅ Analytics
                gtag('consent', 'update', {
                    'analytics_storage': 'granted'
                });
                break;
            case 'targeting':  // ✅ Advertising
                gtag('consent', 'update', {
                    'ad_storage': 'granted',
                    'ad_user_data': 'granted',
                    'ad_personalization': 'granted'
                });
                break;
        }
    }
}

Prueba del modo de consentimiento

// After accepting cookies, check consent state:
console.log(google_tag_manager['GTM-XXXX'].dataLayer.get('consent'));

// Should show:
// {
//   ad_storage: "granted",
//   analytics_storage: "granted",
//   ...
// }

Problemas entre dominios

Problema

«He configurado cookie_domain como '.example.com', pero el banner sigue apareciendo en todos los subdominios. ¡Los usuarios están molestos!»

Pasos de diagnóstico

Paso 1: Verifica el dominio de la cookie

// DevTools → Application → Cookies
// Look for: cookie_consent_level
// Domain column should show: .example.com (with leading dot)

// If it shows: www.example.com (no dot)
// Then cookie_domain parameter isn't working

Paso 2: Comprueba la cookie del subdominio

// On www.example.com:
console.log(document.cookie);
// Should include: cookie_consent_level=...

// Then navigate to shop.example.com:
console.log(document.cookie);
// Should STILL include the same cookie

Paso 3: Prueba en modo incógnito

  1. Abrir una ventana de incógnito
  2. Visita www.example.com
  3. Acepta las cookies
  4. Anota el valor de la cookie
  5. Visita shop.example.com
  6. Comprueba si existe la misma cookie

Causas comunes y soluciones

Causa 1: Falta el punto inicial

// ❌ WRONG
"cookie_domain": "example.com"  // No leading dot

// ✅ CORRECT
"cookie_domain": ".example.com"  // With leading dot

Causa 2: Configuraciones diferentes

Problema

El dominio principal y el subdominio tienen configuraciones diferentes.

// www.example.com has:
cookieconsent.run({
    "website_name": "Main Site",
    "cookie_domain": ".example.com"
});

// shop.example.com has:
cookieconsent.run({
    "website_name": "Shop",  // ❌ Different config
    "cookie_domain": ".example.com"
});

Solución

Utilice una configuración IDÉNTICA en todos los dominios.

// ✅ SOLUTION: Use IDENTICAL configuration on all domains
const SHARED_CONFIG = {
    "notice_banner_type": "headline",
    "consent_type": "express",
    "website_name": "Example",  // Same everywhere
    "cookie_domain": ".example.com",
    // ... rest of config
};

// Use on ALL domains
cookieconsent.run(SHARED_CONFIG);

Causa 3: El navegador bloquea las cookies de terceros

Problema

Safari, Firefox y Brave bloquean las cookies entre sitios de forma predeterminada.

Solución

Esto afecta a DOMINIOS DIFERENTES, no a subdominios.

  • Subdominios (.example.com) = Cookies propias ✅ Debería funcionar
  • Diferentes TLD (example.com frente a example.co.uk) = Terceros ❌ No funcionará
// For actual cross-domain (different TLDs), use backend sync:
"callbacks": {
    "user_consent_saved": () => {
        // Sync to backend
        fetch('https://api.example.com/sync-consent', {
            method: 'POST',
            body: JSON.stringify({
                consent: getConsentState(),
                user_id: getUserId()
            })
        });
    }
}

Causa 4: La cookie no es visible debido a la ruta

// Cookie might be set for specific path
// Check: DevTools → Application → Cookies → Path column

  // Should be: /
// If not, cookie won't work across site

// Force root path (this should be default):
// Note: TermsFeed Cookie Consent should handle this automatically
// But if you're manually setting cookies:
document.cookie = 'cookie_consent_level=...; path=/; domain=.example.com';

Problemas de codificación de caracteres

Problema

«Los caracteres especiales del texto de mi banner se muestran como �� o símbolos extraños»

Solución

Asegúrate de que la codificación sea UTF-8.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">  <!-- ✅ Must have this -->
    <title>My Site</title>
</head>
<body>
    <script src="//www.termsfeed.com/public/cookie-consent/4.2.0/cookie-consent.js" charset="UTF-8"></script>
    <!-- ✅ charset="UTF-8" in script tag -->
</body>
</html>

Para texto personalizado:

cookieconsent.run({
    "website_name": "Café Français",  // ✅ UTF-8 characters work
    "language": "fr"  // Use appropriate language
});