Il banner non viene visualizzato

Problema

  • Il banner dei cookie non viene visualizzato al caricamento della pagina.
  • Gli utenti non vedono la richiesta di consenso.

Passaggi diagnostici

Passaggio 1: Verifica se TermsFeed Cookie Consent è caricato

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

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

Passaggio 2: Verifica la presenza di errori JavaScript

  1. Apri DevTools (F12)
  2. Vai alla scheda Console
  3. Cerca gli errori

Gli errori più comuni includono:

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

Passaggio 3: Verifica il posizionamento dello script di consenso ai cookie di 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>

Cause comuni e soluzioni

Causa 1: L'utente ha già dato il consenso

// 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 ad blocker sta bloccando TermsFeed Cookie Consent

La soluzione è integrare un server proxy per servire TermsFeed Cookie Consent.

Causa 3: La Content Security Policy blocca il caricamento

L'errore in Strumenti per gli sviluppatori > Console potrebbe essere Refused to load the script ... violates the following Content Security Policy directive

La soluzione consiste nell'aggiornare le intestazioni CSP:

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

Causa 4: Configurazione errata

Errori comuni nella configurazione:


// 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: Script in conflitto

Un altro script potrebbe impedire la visualizzazione del banner di consenso ai cookie di TermsFeed.

La soluzione consiste nel verificare l'ordine di caricamento degli script.

// 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)

Modalità debug

Abilita la registrazione di debug:

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

Gli script non vengono bloccati

Problema

"Ho contrassegnato il mio script di Google Analytics con data-cookie-consent='tracking', ma viene comunque attivato prima che l'utente accetti i cookie!"

Passaggi diagnostici

Passaggio 1: Verifica il tagging dello 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" -->

Passaggio 2: Controlla la scheda Rete

  1. Apri DevTools → scheda Rete
  2. Cancella i cookie
  3. Ricarica la pagina (prima di accettare)
  4. Filtra gli script di tracciamento
  5. Gli script con tag NON dovrebbero apparire nella scheda Rete

Passaggio 3: Verifica se vengono impostati i cookie

  1. DevTools → Applicazione → Cookie
  2. Prima dell'accettazione: nessun cookie di Google Analytics
  3. Dopo l'accettazione: compaiono i cookie _ga e _gid

Cause comuni e soluzioni

Causa 1: Script caricato prima del consenso ai cookie

<!-- ❌ 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: Lo script esterno non è bloccato

<!-- ❌ 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: Utilizzo di Google Tag Manager

Il problema comune si verifica quando GTM viene caricato prima del consenso.

La soluzione consiste nel non taggare il contenitore GTM stesso. Invece:

  1. Caricare GTM normalmente (senza taggare)
  2. Configurare i tag ALL'INTERNO di GTM in modo che vengano attivati solo con il consenso
  3. Utilizzare la modalità di consenso integrata o trigger personalizzati
<!-- 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: i cookie sono impostati dal server

Se un server backend imposta i cookie prima dell'esecuzione di JavaScript, la soluzione consiste nel programmare una maggiore logica lato server.

<?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, '/');
}
?>

Il consenso non è persistente

Problema

"L'utente accetta i cookie, ma quando naviga su un'altra pagina o aggiorna la pagina, il banner appare di nuovo!"

Passaggi diagnostici

Passaggio 1: verificare se viene impostato un 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

Passaggio 2: verificare le proprietà del 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

Cause comuni e soluzioni

Causa 1: Percorso del cookie non corrispondente

Problema

Il cookie è impostato per /subdir ma la pagina si trova in /

Soluzione

Assicurarsi che il cookie utilizzi il percorso radice.

// 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: Il browser blocca i cookie

Problema

Le impostazioni sulla privacy del browser impediscono la memorizzazione dei cookie.

Soluzione

L'utente deve modificare le impostazioni del browser.

// 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: Cancellazione dei cookie in conflitto

Problema

Un altro script o un'estensione del browser cancella i cookie.

Soluzione

Verificare cosa sta cancellando i cookie

// 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: Problemi con i sottodomini

Problema

Il cookie impostato su www.example.com non funziona su example.com

Soluzione

Utilizza il parametro cookie_domain.

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

Causa 5: Disallineamento HTTPS/HTTP

Problema:

Il cookie è stato impostato con il flag Secure su HTTPS, ma il sito passa a HTTP.

Soluzione:

Assicurati che il protocollo sia coerente OPPURE rimuovi il flag di sicurezza per il test.

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...
});

La modalità di consenso di Google non funziona

Problema

"Ho implementato la Modalità consenso di Google V2, ma Google Analytics continua a mostrare 0 eventi anche quando gli utenti accettano i cookie."

Passaggi diagnostici

Passaggio 1: verificare l'esistenza della funzione gtag

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

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

Passaggio 2: controllare dataLayer

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

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

Passaggio 3: utilizzare Google Tag Assistant

  1. Installazione: estensione Tag Assistant per Chrome
  2. Abilita il debug
  3. Ricaricare la pagina
  4. Verifica la presenza di eventi in modalità consenso

Cause comuni e soluzioni

Causa 1: Ordine di implementazione errato

<!-- ❌ 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: Parametro callbacks_force mancante

// ❌ 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: Errore di battitura nei tipi di consenso

// ❌ 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: Mappatura delle categorie errata

// 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;
        }
    }
}

Test della modalità di consenso

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

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

Problemi tra domini

Problema

"Ho impostato cookie_domain su '.example.com', ma il banner continua a comparire su ogni sottodominio. Gli utenti sono infastiditi!"

Passaggi diagnostici

Passaggio 1: Verifica il dominio dei 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

Passaggio 2: Controlla i cookie dal sottodominio

// 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

Passaggio 3: Esegui un test in modalità di navigazione in incognito

  1. Apri una finestra in incognito
  2. Visita www.example.com
  3. Accetta i cookie
  4. Annotare il valore del cookie
  5. Visita shop.example.com
  6. Verifica se esiste lo stesso cookie

Cause comuni e soluzioni

Causa 1: Manca il punto iniziale

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

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

Causa 2: Configurazioni diverse

Problema

Il dominio principale e il sottodominio hanno configurazioni diverse.

// 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"
});

Soluzione

Utilizza una configurazione IDENTICA su tutti i domini.

// ✅ 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: Browser che blocca i cookie di terze parti

Problema

Safari, Firefox e Brave bloccano i cookie cross-site per impostazione predefinita.

Soluzione

Questo riguarda domini DIVERSI, non i sottodomini.

  • Sottodomini (.example.com) = Cookie di prima parte ✅ Dovrebbe funzionare
  • TLD diversi (example.com vs example.co.uk) = Terze parti ❌ Non funzionerà
// 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: Cookie non visibile a causa del percorso

// 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';

Problemi di codifica dei caratteri

Problema

"I caratteri speciali nel testo del mio banner vengono visualizzati come �� o simboli strani"

Soluzione

Assicurati che la codifica sia 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>

Per il testo personalizzato:

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