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 pop up doesn't appear on home page. #34

Closed panseit closed 3 years ago

panseit commented 3 years ago

Hello,

I don't know if it's a bug of something with my setup but when I visit my homepage the cookie pop up doesn't appear. It appears on all the other pages except the root directory of my site (I can provide the link if you want). Also if I want to add a cookie for AdSense is it possible to do it by using your addon?

EDIT1 : I'm also getting this error : cookieconsent.js:27 Uncaught TypeError: Cannot read property 'appendChild' of null at Da (cookieconsent.js:27) at Object.n.run (cookieconsent.js:30) at cookies.js:5

EDIT2 : Google Analytics seems to not getting data at all.

But I'm using your template file....

orestbida commented 3 years ago

@panseit To tell you what's wrong I'd need the link or the config. settings.

panseit commented 3 years ago

`// obtain cookieconsent plugin var cc = initCookieConsent();

// run plugin with config object cc.run({ autorun : true, delay : 0, current_lang : 'en', auto_language : true, autoclear_cookies : true, cookie_expiration : 182, autoload_css: true, theme_css: 'https://cdn.jsdelivr.net/gh/orestbida/cookieconsent@v2.4.5/dist/cookieconsent.css',

gui_options : {
    consent_modal : {
        layout : 'box',
        position : 'bottom right',
        transition : 'slide'
    },
    settings_modal : {
        layout : 'box',
        position : 'left',
        transition : 'right'
    }
},

onAccept: function(cookie){ 
    //console.log("onAccept fired ...");
    if(cc.allowedCategory('analytics_cookies')){
        cc.loadScript('https://www.google-analytics.com/analytics.js', function(){      
            ga('create', '', 'auto');
            ga('send', 'pageview');
            //console.log("analytics.js loaded");
        });
    }
},

onChange: function(cookie){ 
    //console.log("onChange fired ...");
    // do something ...
},

languages : {
    'en' : {    
        consent_modal : {
            title :  "We use cookies",
            description :  'Greetings, Portal Master! Skylands.io uses essential cookies to ensure its proper operation and tracking cookies to understand how you interact with it. The latter will be set only upon approval. <a aria-label="Cookie policy" data-cc="c-settings" class="cc-link" href="#">Change preferences</a>',
            primary_btn: {
                text: 'Accept all',
                role: 'accept_all'              //'accept_selected' or 'accept_all'
            },
            secondary_btn: {
                text : 'Accept necessary',
                role : 'accept_necessary'               //'settings' or 'accept_necessary'
            }
        },
        settings_modal : {
            title : '<div>Cookie settings</div>',
            save_settings_btn : "Save settings",
            accept_all_btn : "Accept all",
            cookie_table_headers : [
                {col1: "Name" }, 
                {col2: "Domain" }, 
                {col3: "Expiration" }, 
                {col4: "Description" },
                {col5: "Privacy policy"}
            ],
            blocks : [
                {
                    title : "Cookie usage",
                    description: 'We use cookies to ensure the basic functionalities of the website and to enhance your online experience. You can choose for each category to opt-in/out whenever you want. For more details about cookies and how we use them, read the full <a href="../privacy-policy.html" class="cc-link">cookie policy</a>.'
                },{
                    title : "Strictly necessary cookies",
                    description: 'These cookies are essential for the proper functioning of our website. Without these cookies, the website would not work properly.',
                    toggle : {
                        value : 'necessary_cookies',
                        enabled : true,
                        readonly: true                          //cookie categories with readonly=true are all treated as "necessary cookies"
                    }
                },{
                    title : "Preferences cookies",
                    description: 'These cookies allow the website to remember the choices you have made in the past.',
                    toggle : {
                        value : 'preferences_cookies',  //there are no default categories => you specify them
                        enabled : true,
                        readonly: false
                    }
                },{
                    title : "Analytics cookies",
                    description: 'These cookies cookies collect information about how you use the website, which pages you visited and which links you clicked on. All of the data is anonymized and cannot be used to identify you.',
                    toggle : {
                        value : 'analytics_cookies',
                        enabled : false,
                        readonly: false
                    },
                    cookie_table: [
                        {
                            col1: '_ga',
                            col2: 'google.com',
                            col3: '2 years',
                            col4: 'Permanent cookie used to distinguish users.' ,
                            col5: '<a href="https://policies.google.com/privacy?hl=en-US" style="word-break: break-all;">Privacy Policy</a>',
                        },
                        {
                            col1: '_gat',
                            col2: 'google.com',
                            col3: '1 minute',
                            col4: 'Permant Cookie used to throttle request rate. If Google Analytics is deployed via Google Tag Manager, this cookie will be named _dc_gtm_<property- id>.' ,
                            col5: '<a href="https://policies.google.com/privacy?hl=en-US" style="word-break: break-all;">Privacy Policy</a>',
                        },
                        {
                            col1: '_gid',
                            col2: 'google.com',
                            col3: '1 day',
                            col4: 'Permanent Cookie used to distinguish users.' ,
                            col5: '<a href="https://policies.google.com/privacy?hl=en-US" style="word-break: break-all;">Privacy Policy</a>',
                        }
                    ]
                },{
                    title : "More information",
                    description: 'For any queries in relation to our policy on cookies and your choices, please <a class="cc-link" href="mailto:privacy@skylands.io">contact me</a>.',
                }
            ]
        }
    }
}

});`

I have placed my GA id at ga('create', '', 'auto'); The website is the www.skylands.io

orestbida commented 3 years ago

@panseit

there's nothing wrong with your config. The issue is caused by the fact that you have placed the config. (cookies.js containing the config) in the head section of the page. The plugin immediately runs and tries to access body (which is not yet created). The solution is to wait for the body tag to be created first.

Fix 1: add the defer attribute to both cookieconsent.js and cookies.js (this also improves performance, defer tells the browser to not run these scripts until the body is loaded)

<script src="https://cdn.jsdelivr.net/gh/orestbida/cookieconsent@v2.4.5/dist/cookieconsent.js" defer></script>
<script src="assets/js/cookies.js" defer></script>

Fix 2: move both cookieconsent.js and script.js at the bottom of <body> (adding defer is still highly recommended)

Fix 3: you can leave the files where they are right now, but you have to wrap all the code inside cookie.js with this function:

// wait for page load
document.addEventListener('load', function(){
   // cookie.js code goes here
});

Also, you're loading the cookieconsent.css twice:

here:

<link href="https://cdn.jsdelivr.net/gh/orestbida/cookieconsent@v2.4.5/dist/cookieconsent.css" rel="stylesheet">

and here:

cc.run({
    ...
    theme_css: 'https://cdn.jsdelivr.net/gh/orestbida/cookieconsent@v2.4.5/dist/cookieconsent.css'
    ...

If you care about performance, I'd add the defer attribute (like suggested in the first fix) and leave the loading of the cookieconsent.css style to the plugin => remove <link href="https://cdn.jsdelivr.net/gh/orestbida/c...

panseit commented 3 years ago

Hm...Fixed the error but I still cannot see data on Google Analytics. Shouldn't I load Global site tag (gtag.js) (https://support.google.com/analytics/answer/9744165?hl=en&utm_id=ad#cms&zippy=%2Cadd-your-tag-to-a-website-builder-or-cms-hosted-website-for-example-wordpress-shopify-etc) somewhere in the addon or I'm missing something?

orestbida commented 3 years ago

Oh, you're loading analytics.js but configuring it with google tag manager tracking code ... which of course doesn't work.

So either use gtag.js or analytics.js.

If you want to use gtag.js then you can do so like described here: https://github.com/orestbida/cookieconsent#manage-third-party-scripts

if this is your gtag.js tracking code:

<script>
        // Google Tag Manager (configured with GA internally)
        (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-XXXXXXX');
</script>

add type="text/plain" and data-cookiecategory attribute like this:

<script type="text/plain" data-cookiecategory="analytics_cookies">

you will also need to enable page_scripts inside the .run() method. There is a full example showing how this works in the second demo: https://github.com/orestbida/cookieconsent/blob/1132dab52a0096938b28a8f52ddc5fc553916822/demo/index2.html#L544-L552 https://github.com/orestbida/cookieconsent/blob/1132dab52a0096938b28a8f52ddc5fc553916822/demo/app2.js#L27

orestbida commented 3 years ago

@panseit

to be even more clear, if you still can't make it work, this is how you could set up both google analytics (gtag.js) and google ads. (it's basically the same copy-paste code provided by google, with some minor changes)

<body>
  <!-- Global site tag (gtag.js) - Google Analytics -->
  <script type="text/plain" data-cookiecategory="analytics_cookies" data-src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID" async></script>
  <script type="text/plain" data-cookiecategory="analytics_cookies">
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', 'GA_MEASUREMENT_ID');
  </script>

  <!-- Google Ads -->
  <script type="text/plain" data-cookiecategory="analytics_cookies" data-ad-client="ca-pub-xxxxxxxxxxxx" data-src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" async></script>
  <!--push 1 ad when enabled -->
  <script type="text/plain" data-cookiecategory="analytics_cookies">
  (adsbygoogle = window.adsbygoogle || []).push({});
  </script>
</body>

You can also configure these using the .loadScript() function, but that method requires a bit more work to do.

orestbida commented 3 years ago

@panseit and this is the same configuration but using the loadScript() method:

if(cc.allowedCategory('analytics_cookies')){

    // Load google tag manager
    cc.loadScript('https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID', function(){  //modify GA_MEASUREMENT_ID
        // gtag.js loaded => config and run
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'GA_MEASUREMENT_ID');  //modify GA_MEASUREMENT_ID
    });

    // Load google ads
    cc.loadScript('https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', function(){
        // adsbygoogle.js loaded => push 1 ad
        (adsbygoogle = window.adsbygoogle || []).push({});
    }, [
        {name: 'data-ad-client', value: 'ca-pub-xxxxxxxxxxxx'}    // modify ca-pub-xxxxxxxxxxxx
    ]);

}
panseit commented 3 years ago

Thank you will try them out and report back!! Thank you for all the help really!!! <3 <3

panseit commented 3 years ago

It seems that work!! Cannot test Adsense atm but I bet it works too :)

panseit commented 3 years ago

Sorry for posting here but don't know if I should open a new ticket for this. I'm getting this error regarding Google Adsense. Don't know if it's bad configuration or because my Adsense account is under review/activation atm.

P message: "adsbygoogle.push() error: All ins elements in the DOM with class=adsbygoogle already have ads in them." name: "TagError" pbr: true stack: "TagError: adsbygoogle.push() error: All ins elements in the DOM with class=adsbygoogle already have ads in them.\n at Vm (https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js:228:210)\n at Mm (https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js:224:265)\n at https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js:220:47\n at Ge.n.la (https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js:66:804)\n at Pe (https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js:74:107)\n at Im (https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js:220:29)\n at Object.push (https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js:233:206)\n at HTMLScriptElement.cc.loadScript.name (https://www.skylands.io/assets/js/cookies.js:2:183)" __proto__: Error constructor: ƒ P(a) __proto__: constructor: ƒ Error() message: "" name: "Error" toString: ƒ toString() __proto__: Object

orestbida commented 3 years ago

@panseit

When the cookieconsent is accepted it loads adsbygoogle.js and then runs this code:

(adsbygoogle = window.adsbygoogle || []).push({});

which needs at least one <ins> tag to be present in the page (an ins tag contains the ad itself).

Since there are no ins tags, an error is thrown: adsbygoogle.push() error: All ins elements in the … with class=adsbygoogle already have ads in them. ..

I don't know your previous googleads configuration. I showed you one the configs. of google ads which uses ins tags. Surely there are other possible configs. This is the one which I proposed to you: https://support.google.com/adsense/answer/9183243?hl=en

You should be able to remove this line:

(adsbygoogle = window.adsbygoogle || []).push({});

if you don't plan on manually specifying the ads' location. Autoads should still get triggered (not a google ads expert ...)

panseit commented 3 years ago

I didn't have a previous google ads configuration :P It's my first web project honestly.

panseit commented 3 years ago

Hmmm....I got rejected from Google AdSense and the reason was that they couldn't find the code snippet on my site....But it should be since I'm using cookieconsent. Am I wrong?

orestbida commented 3 years ago

I don't know how google checks for the code snippet (probably a simple page scan automated by tools). But it makes sense that it is not able to detect the code since it's actually hidden inside the cookieconsent + disabled.

You can let google find the code by loading googleads like the first proposed solution:

<body>

  <!-- Google Ads -->
<script type="text/plain" data-cookiecategory="analytics_cookies" data-ad-client="ca-pub-xxxxxxxxxxxx" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" async></script>
</body>

or

<body>

  <!-- Google Ads -->
  <script type="text/plain" data-cookiecategory="analytics_cookies" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" async></script>

  <!--start ads -->
  <script type="text/plain" data-cookiecategory="analytics_cookies">
    (adsbygoogle=window.adsbygoogle||[]).push({google_ad_client:'ca-pub-YOUR-ADSENSE-ID',enable_page_level_ads:true});
  </script>
</body>

Of course you will need to remove the script loading inside the cookieconsent: cc.loadScript('https://pagead2.googlesyndication.com ....

If google adsense requires the googleads code to be enabled + running ... then you will have to get "verified/accepted" first by simply loading google adsense scripts like you would usually (without being managed by the cookieconsent) and then manage the code (after you have been accepted) with the cookieconsent like described above.

panseit commented 3 years ago

I see I see....Which of the two solutions do you suggest/works better in your opinion? :)

orestbida commented 3 years ago

mhm, they should be the exact same thing (based on what i found online). I guess you could try the second option since it has more visible code i guess ??

orestbida commented 3 years ago

remember to also set page_scripts : true inside the cookieconsent, if you haven't alredy

panseit commented 3 years ago

Hmmm....Google Adsense requires the script to be on head so I will put there till I get accepted I think.

panseit commented 3 years ago

Again ty and sorry for bothering you.

orestbida commented 3 years ago

no problemo 👍