orestbida / cookieconsent

:cookie: Simple cross-browser cookie-consent plugin written in vanilla js
https://playground.cookieconsent.orestbida.com/
MIT License
4k stars 410 forks source link

Cookie consent with GTM #336

Closed PerpetuumPromile closed 2 years ago

PerpetuumPromile commented 2 years ago

Hey, I have bunch of problems which I cant get around, maybe I dont know how to use this cookieconsent or maybe you can help me.

The 1st problem: After I allow marketing cookies(ad_storage) only and not analytics, nothing really happens, the tags wont show. If I allow analytics everything works fine as it should, analytics_storage is granted and the tags are showing in the Tag Assistant. I just cant get around why its not working for ad_storage also.

The 2nd problem: When I allow analytics(), I have 2 tags fired(or rather my ID is tracked twice). It is probaby happening becous of function gtag, but then I cant deny or grant permission.

I was looking into the code you typed in this thread: https://github.com/orestbida/cookieconsent/issues/110

I am new to these things, so sorry if its not appropriate for a thread.

Also my code is here: https://pastebin.com/16s5hLUq Thanks

orestbida commented 2 years ago

Hi @PerpetuumPromile,

you can only have one data-cookiecategory attribute. The second one with the value ads is ignored.

Since you're using google consent mode with ads and analytics disabled by default, you can completely remove the data-cookiecategory attribute.

This should fix the issue, and still be GDPR-compliant.

Another issue is that you're declaring the plugin's own cookie in the analytics category. This will cause the cookie to be erased when the user opts-out of analytics, and the modal will re-appear in the next page visit. You should declare the cookie in the necessary category, as it is just a technical/needed cookie and does not track the user.

I re-factored your code a bit to also allow the user to disable google analytics/ads in a later moment. Fixed version:

<script>
    // Define dataLayer and the gtag function.
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}

    // Default ad_storage to 'denied'.
    gtag('consent', 'default', {
        'ad_storage': 'denied',
        'analytics_storage': 'denied'
    });
</script>

<!-- Google Tag Manager -->
<script type="text/plain">(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-5S7X8NH');</script>

<script defer type="text/javascript" src="/js/cookieconsent.js" charset="UTF-8"></script>
<script>
    window.addEventListener('load', function(){

        // obtain plugin
        var cc = initCookieConsent();

        // run plugin with your configuration
        cc.run({
            current_lang: 'cs',
            autoclear_cookies: true,                   // default: false
            page_scripts: true,                        // default: false

            //mode: 'opt-in'                          // default: 'opt-in'; value: 'opt-in' or 'opt-out'
            //delay: 0,                               // default: 0
            // auto_language: '',                      // default: null; could also be 'browser' or 'document'
            autorun: true,                          // default: true
            //force_consent: false,                   // default: false
            // hide_from_bots: false,                  // default: false
            remove_cookie_tables: false,            // default: false
            //cookie_name: 'cc_cookie',               // default: 'cc_cookie'
            cookie_expiration: 365,                 // default: 182 (days)
            // cookie_necessary_only_expiration: 182   // default: disabled
            // cookie_domain: location.hostname,       // default: current domain
            // cookie_path: '/',                       // default: root
            // cookie_same_site: 'Lax',                // default: 'Lax'
            // use_rfc_cookie: false,                  // default: false
            // revision: 0,                            // default: 0

            gui_options: {
                consent_modal: {
                    layout: 'box',               // box/cloud/bar
                    position: 'bottom right',     // bottom/middle/top + left/right/center
                    transition: 'slide',           // zoom/slide
                },
                settings_modal: {
                    layout: 'box',                 // box/bar
                    //position: 'right',           // left/right
                    transition: 'slide'            // zoom/slide
                }
            },

            onFirstAction: function(user_preferences, cookie){
                // callback triggered only once on the first accept/reject action
            },

            onAccept: function (cookie) {
                if(cc.allowedCategory('analytics')){
                    enableAnalytics();
                }

                if(cc.allowedCategory('ads')){
                    enableAds();
                }
            },

            onChange: function (cookie, changed_categories) {
                if(cc.allowedCategory('analytics')){
                    enableAnalytics();
                }else{
                    disableAnalytics();
                }

                if(cc.allowedCategory('ads')){
                    enableAds();
                }else{
                    disableAds();
                }
            },

            languages: {
                'cs': {
                    consent_modal: {
                        title: 'Používáme cookies!',
                        description: 'Dobrý den, tento web používá nezbytné soubory cookie k zajištění správného fungování a sledovací soubory cookie, abychom pochopili, jak s nimi komunikujete. Cookies budou nastaveny až po souhlasu. <button type="button" data-cc="c-settings" class="cc-link">Spravovat předvolby souborů cookie</button>',
                        primary_btn: {
                            text: 'Přijmout vše',
                            role: 'accept_all'              // 'accept_selected' or 'accept_all'
                        },
                        secondary_btn: {
                            text: 'Odmítnout vše',
                            role: 'accept_necessary'        // 'settings' or 'accept_necessary'
                        }
                    },
                    settings_modal: {
                        title: 'Předvolby souborů cookie',
                        save_settings_btn: 'Uložit nastavení',
                        accept_all_btn: 'Přijmout vše',
                        reject_all_btn: 'Odmítnout vše',
                        close_btn_label: 'Zavřít',
                        cookie_table_headers: [
                                {col1: 'Name'},
                                {col2: 'Domain'},
                                {col3: 'Expiration'}
                        ],
                        blocks: [
                            {
                                title: 'Co jsou to cookies? ',
                                description: 'Soubory cookies a další technologie nám pomáhají zlepšovat naše služby, pomáhají nám analyzovat výkon webu a umožňují nám pomáhat zákazníkům ve výběru správného zboží. V nastavení si můžete vybrat, které cookies můžeme používat. Svůj souhlas můžete kdykoliv odvolat.\n Přečtěte si naše <a href="https://www.riverfront.cz/ochrana-soukromi/" class="cc-link">zásady o zpracování osobních údajů </a>.'
                            }, {
                                title: 'Nezbytně nutné soubory cookie',
                                description: ' Tyto cookies jsou nezbytně nutné pro správnou funkci webu - zajišťují správné zobrazení, odesílání formulářů a podobně. Technické cookies není možné vypnout.',
                                toggle: {
                                    value: 'necessary',
                                    enabled: true,
                                    readonly: true          // cookie categories with readonly=true are all treated as "necessary cookies"
                                },
                                cookie_table: [             // list of all expected cookies
                                    {
                                        col1: 'cc_cookie',
                                        col2: 'www.riverfront.cz',
                                        col3: '365 days',
                                        path: '/'
                                    }
                                ]
                            }, {
                                title: 'Statické cookies',
                                description: 'Tyto soubory cookie umožňují webu zapamatovat si volby, které jste provedli v minulosti.',
                                toggle: {
                                    value: 'analytics',     // your cookie category
                                    enabled: false,
                                    readonly: false
                                },
                                cookie_table: [             // list of all expected cookies
                                    {
                                        col1: '^_ga',       // match all cookies starting with "_ga"
                                        col2: 'google.com',
                                        col3: '2 years',
                                        is_regex: true,
                                    },
                                    {
                                        col1: '_gid',
                                        col2: 'google.com',
                                        col3: '1 day',
                                    }
                                ]
                            }, {
                                title: 'Marketingové cookies',
                                description: 'Tyto soubory cookie shromažďují informace o tom, jak web používáte, které stránky jste navštívili a na které odkazy jste klikli. Všechna data jsou anonymizována a nelze je použít k vaší identifikaci',
                                toggle: {
                                    value: 'ads',
                                    enabled: false,
                                    readonly: false
                                }
                            }
                        ]
                    }
                }
            }
        });
    });

    /* Helper functions to avoid repeating the same ga code */
    function enableAnalytics(){
        console.log("enabled analytics")
        gtag('consent', 'update', {
            'analytics_storage': 'granted'
        });
    }

    function disableAnalytics(){
        console.log("disabled analytics")
        gtag('consent', 'update', {
            'analytics_storage': 'denied'
        });
    }

    function enableAds(){
        console.log("enabled ads")
        gtag('consent', 'update', {
            'ad_storage': 'granted'
        });
    }

    function disableAds(){
        console.log("disabled ads")
        gtag('consent', 'update', {
            'ad_storage': 'denied'
        });
    }
</script>
PerpetuumPromile commented 2 years ago

Thanks for reply, but I tried something like this without the data_cookiecatogory in GTM script like I had, but I got the same result as this code you typed above. The googe tags just wont fire and show in Google Tag Assistant. When I delete the script type from GTM, 2 tags will fire when page is loaded even withou the consent and the 3rd will fire when I accept marketing cookies. Or the tags just had nothing to do with cookies. Ngl I am kinda lost.