Magento2: Google Universal Analytics does not track when Cookie Restriction is enabled

Created on 12 Jul 2016  路  32Comments  路  Source: magento/magento2

Steps to reproduce

  1. Install Magento v2.1 from composer.
  2. Configure the Admin Panel with a valid Google analytics ID and set mode to _'Universal Analytics' under 'Stores => Configuration => Sales => Google Api => Google Analytics'_
  3. Set cookie restriction mode to 'yes' under '_Stores => Configuration => General => Web => Default Cookie Settings => Cookie Restriction Mode_.
  4. Clear all caches
  5. View any front end page
  6. Click the 'Allow Cookies' in the cookie restriction banner
  7. Wait for page to reload and use Google Analytics debug plugin to look for beacons sent to GA.
    (https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna?hl=en) or view live tracking results in the Google analytics control panel.

    Expected result

  8. Tracking Beacons are sent to GA (visible in the browser console is using the GA dEbug tool )
    e.g.

Initializing Google Analytics.
analytics_debug.js:9 Running command: ga("create", "UA-<yourGAid>", "auto")
analytics_debug.js:9 Creating new tracker: t0
analytics_debug.js:9 New visitor. Generating new clientId
analytics_debug.js:9 Auto cookieDomain found: "sitedomain.com"
analytics_debug.js:9 Running command: ga("send", "pageview")
analytics_debug.js:9 Setting throttling cookie: "_gat"
analytics_debug.js:9 
Sent beacon:
v=1&_v=j44d&a=1955779100&t=pageview&_s=1&dl=http%3A%2F%2Fsiteurl%2F&ul=en-us&de=UTF-8&dt=Home%20Page&sd=24-bit&sr=1050x1680&vp=1050x1050&je=0&fl=22.0%20r0&_u=AEAAAEABI~&jid=1985252792&cid=1406517672.1468336046&tid=UA-<yourGAid>&_r=1&z=1708727464


analytics_debug.js:9 _j1              (&jid) 1985252792
analytics_debug.js:9 adSenseId        (&a)   1955779100
analytics_debug.js:9 apiVersion       (&v)   1
analytics_debug.js:9 clientId         (&cid) 1406517672.1468336046
analytics_debug.js:9 encoding         (&de)  UTF-8
analytics_debug.js:9 flashVersion     (&fl)  22.0 r0
analytics_debug.js:9 hitType          (&t)   pageview
analytics_debug.js:9 javaEnabled      (&je)  0
analytics_debug.js:9 language         (&ul)  en-us
analytics_debug.js:9 location         (&dl)  http://####SITEURL###/
analytics_debug.js:9 screenColors     (&sd)  24-bit
analytics_debug.js:9 screenResolution (&sr)  1050x1680
analytics_debug.js:9 title            (&dt)  Home Page
analytics_debug.js:9 trackingId       (&tid) UA-<yourGAid>
analytics_debug.js:9 viewportSize     (&vp)  1050x1050
analytics_debug.js:9 Registered new plugin: ga(provide, "render", Function)

and

Live Page tracking statistics to change in Google Analytics Web Console

Actual result

  1. No Beacon sent, shown in debug console or recorded in Google analytics.

NB. This case is a duplicate of a closed but unresolved case: https://github.com/magento/magento2/issues/2518

Fixed in 2.1.x Fixed in 2.2.x Format is not valid Ready for Work 2.1 bug report

Most helpful comment

Confirmed here. We need the cookie allow feature thats why using true doesn't work for us. The root cause for this problem lies in module-cookie/view/frontend/web/js/notices.js, where the cookieValue is not saved as a JSON string. After confirming cookies the value just gets saved as "[object Object]", which cannot be interpreted by _getAcceptedSaveCookiesWebsites in module-cookie/Helper/Cookie.php

auswahl_052
auswahl_053

All 32 comments

Same problem here. This needs to be reviewed why is not injecting the google analytics code...

Same here. The Analytics Code is just missing in the source code of the rendered page.

A fix would be highly apperciated!

A quick fix is to copy the file:
vendor/magento/module-google-analytics/view/frontend/templates/ga.phtml
to your own theme:
app/design/frontend/{Vendor}/{theme}/Magento_GoogleAnalytics/templates/ga.phtml

And then replace this line:

<?php if (!$this->helper('Magento\Cookie\Helper\Cookie')->isUserNotAllowSaveCookie()): ?>

with:

<?php if (true): // !$this->helper('Magento\Cookie\Helper\Cookie')->isUserNotAllowSaveCookie()): ?>

Watch out, this will _always_ output the GA code, even if the user hasn't accepted the cookie message. I'm ok with this, but you should probably check with your legal departement if this is ok to do or not.

@hostep - your fix is working... THX
Can confirm the bug.

Confirmed here. We need the cookie allow feature thats why using true doesn't work for us. The root cause for this problem lies in module-cookie/view/frontend/web/js/notices.js, where the cookieValue is not saved as a JSON string. After confirming cookies the value just gets saved as "[object Object]", which cannot be interpreted by _getAcceptedSaveCookiesWebsites in module-cookie/Helper/Cookie.php

auswahl_052
auswahl_053

Isn't this in breach of the EU cookie law? Web owners can remove the check themselves, but I don't think Magento should do it.

This is still a problem. Any progress?

Still issue in latest version. @hostep fix works. But now its more a cookie notice, not restriction.

Reopening, as fix for 2.1 is not available yet.

Is this resolved yet? I'm creating a store in EU and I'm running into the same problem with Magento 2.1.7.
I've lost overview somehow, so I'm only asking if it's worth waiting for the next update or if I finagle around it.

@storepeinture Looks like the fix is currently available only in the develop branch, which is going to be 2.2.

@ishakhsuvarov I applied the stringify change specified in commit a4daf56 but it still does not work.

@coachdesign You may also try to apply PR magento/magento2#9711
I am not totally sure on this one, but several different fixes may be needed to get it going.

I can confirm this is, again, not implemented in 2.1.7. Reported over one year ago - and not fixed. 5 shops left on magento2 for our company - 13 switched and running now on other ecommerce systems at the moment as the magento team does not get the job done in fixing bugs since over one year.

It will never be fixed in any future 2.1 release. 2.1 receives only security fixes.
You shall upgrade to 2.2 ... which has lots of breaking changes but it's worth.

@SchumacherFM: can you please stop spreading such news, this is definitely not true. 2.1 still receives bug fixes, just look at what's going on on the 2.1.8-preview branch, you'll see a lot of bug fixes. They just need to start releasing it very soon as it has been almost 4 months since the last bugfix release...

Same here, how can such a bug couldn't be solved more than a year after being noticed ?
Do anyone had tried with some cookie module with success ?

Used https://cookieconsent.insites.com/
Worked like a charm out of the box.

Hi @tommybds thanks for the link - i think we go for it too. The magento internal cookie notice is really crap.

Could you maybe tell the community how you implemented this?

Would be great!

Thanks!

Hello @andidhouse , you can generate a little script on my link, and choose the color or the text. Once you're done, copy the code and paste it in the html header of your website view in content->design->conf
You can see the effect here for exemple : https://tommy-bordas.fr/

Hi @tommybds thanks - i just wondered if it would make more sense to implement this directly into the template - but your solution works like expected.

From SEO perspective i would not want to load two extra files (CSS and JS) from another server for the cookie notice. I try to get a developer today - i think it is simple to host both css and script on the magento server so this would be the best solution. Also the css is not really mobile friendly.
Thanks again!

Hi @andidhouse If you find a way to simplify the css let me know :)

Internal ticket to track issue progress: MAGETWO-69374

I've published a module https://github.com/magma/magento2-cookie-restriction-fix while we are waiting for a fix. It just replaces notices.js.

I've upgraded to Magento 2.2.1 but the problem still persists.

Hi Guys i have edited a little bit the fix of @hostep to be 100% sure that your Customers will not see Google Analytics if they have not accepted cookies.
Unfortunately this helper doesn't work:
$this->helper('Magento\Cookie\Helper\Cookie')->isUserNotAllowSaveCookie()
And the result is always "true" despite you have accepted or not cookies.

An easy fix is to copy the file:
vendor/magento/module-google-analytics/view/frontend/templates/ga.phtml
to your own theme:
app/design/frontend/{Vendor}/{theme}/Magento_GoogleAnalytics/templates/ga.phtml

And then replace this line:

<?php if (!$this->helper('Magento\Cookie\Helper\Cookie')->isUserNotAllowSaveCookie()): ?>
with:

<?php if (isset($_COOKIE["user_allowed_save_cookie"])): // !$this->helper('Magento\Cookie\Helper\Cookie')->isUserNotAllowSaveCookie()): ?>

Under google analytics <script>...</script>, inside php if condition, you can also put other external javascript scripts that use cookies, for example a livechat that need the cookie policy accepted.

Im using Magento 2.2.2 and i can confirm this problem still exist so why the label that it's fixed in 2.2?x?!

@ NickyBass Can you tell if magento 2.2.2 this file: vendor/magento/module-google-analytics/view/frontend/templates/ga.phtml has this if statement as I have 2.2.2 and this file is as bellow:

<?php
/**
 * Copyright 漏 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php /** @var $block \Magento\GoogleAnalytics\Block\Ga */ ?>
<?php $accountId = $block->getConfig(\Magento\GoogleAnalytics\Helper\Data::XML_PATH_ACCOUNT) ?>
<!-- BEGIN GOOGLE ANALYTICS CODE -->
<script type="text/x-magento-init">
{
    "*": {
        "Magento_GoogleAnalytics/js/google-analytics": {
            "isCookieRestrictionModeEnabled": <?= (int)$block->isCookieRestrictionModeEnabled() ?>,
            "currentWebsite": <?= (int)$block->getCurrentWebsiteId() ?>,
            "cookieName": "<?= /* @escapeNotVerified */ \Magento\Cookie\Helper\Cookie::IS_USER_ALLOWED_SAVE_COOKIE ?>",
            "ordersTrackingData": <?= /* @escapeNotVerified */ json_encode($block->getOrdersTrackingData()) ?>,
            "pageTrackingData": <?= /* @escapeNotVerified */ json_encode($block->getPageTrackingData($accountId)) ?>
        }
    }
}
</script>
<!-- END GOOGLE ANALYTICS CODE -->

Also if you look at magento core file here : https://github.com/magento/magento2/blob/2.2-develop/app/code/Magento/GoogleAnalytics/view/frontend/templates/ga.phtml

The if statement doesn't exist.

The cookie user_allowed_save_cookie only add if the user click the accept button what is the fix so it adds the cookie user_allowed_save_cookie without click accept it?

Thanks;

@lano-vargas The fix i wrote was good for 2.1.x actually i don't have a solution for 2.2.2 i think the problem is varnish or the cache.

I have the same problem on 2.2.2. Any solution?

Have a related problem. My understanding is that GA doesn't need to be blocked in cookie restriction mode if you turn off data sharing, anonymize the IP, disable user ID function, disable sharing for ad purposes.

So how can I stop Magento 2.2.5 blocking GA in cookie restriction mode?

In notice.phtml

helper(\Magento\Cookie\Helper\Cookie::class)->isCookieRestrictionModeEnabled()): ?>
getPrivacyPolicyLink()); ?>

tabindex="-1"
class="message global cookie"
id="notice-cookie-block"
style="display: none;">


escapeHtml(__('We use cookies to make your experience better.')) ?>
escapeHtml(__('To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies.')) ?>

          <span><?= $block->escapeHtml(__('Google Analytics is active, if you want to desactivate it click')) ?></span>
          <a href="<?= $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]) ?>?ga=1" title="<?= $block->escapeHtml(__('Google Analytics')) ?>">
              <?= $block->escapeHtml(__('here')) ?>.
          </a>
        </p>
        <div class="actions">
            <button id="btn-cookie-allow" class="action allow primary">
                <span><?= $block->escapeHtml(__('Allow Cookies')) ?></span>
            </button>
        </div>
    </div>
</div>
<script type="text/x-magento-init">
    {
        "#notice-cookie-block": {
            "cookieNotices": {
                "cookieAllowButtonSelector": "#btn-cookie-allow",
                "cookieName": "<?= /* @noEscape */ \Magento\Cookie\Helper\Cookie::IS_USER_ALLOWED_SAVE_COOKIE ?>",
                "cookieValue": <?= /* @noEscape */ $this->helper(\Magento\Cookie\Helper\Cookie::class)->getAcceptedSaveCookiesWebsiteIds() ?>,
                "cookieLifetime": <?= /* @noEscape */ $this->helper(\Magento\Cookie\Helper\Cookie::class)->getCookieRestrictionLifetime() ?>,
                "noCookiesUrl": "<?= $block->escapeJs($block->escapeUrl($block->getUrl('cookie/index/noCookies'))) ?>"
            }
        }
    }
</script>

`

and in ga.phtml

<?php /** @var $block \Magento\GoogleAnalytics\Block\Ga */ ?>
<?php $accountId = $block->getConfig(\Magento\GoogleAnalytics\Helper\Data::XML_PATH_ACCOUNT) ?>
<!-- BEGIN GOOGLE ANALYTICS CODE -->
<script type="text/x-magento-init">
{
    "*": {
        "Magento_GoogleAnalytics/js/google-analytics": {
            "isCookieRestrictionModeEnabled": <?= (int)$block->isCookieRestrictionModeEnabled() ?>,
            "currentWebsite": <?= (int)$block->getCurrentWebsiteId() ?>,
            "cookieName": "<?= /* @escapeNotVerified */ \Magento\Cookie\Helper\Cookie::IS_USER_ALLOWED_SAVE_COOKIE ?>",
            "ordersTrackingData": <?= /* @escapeNotVerified */ json_encode($block->getOrdersTrackingData()) ?>,
            "pageTrackingData": <?= /* @escapeNotVerified */ json_encode($block->getPageTrackingData($accountId)) ?>
        }
    }
}
</script>
<!-- END GOOGLE ANALYTICS CODE -->
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cookieManager = $objectManager->get('Magento\Framework\Stdlib\CookieManagerInterface');

if($block->isCookieRestrictionModeEnabled() == 1 && $cookieManager->getCookie('user_allowed_save_cookie') === NULL): ?>

<script type="text/javascript">
    require([
        'jquery',
        'jquery/jquery.cookie'
    ], function ($) { 

        $(document).ready(function(){ 
            var check_cookie = $.cookie('ga_default'); // Get Cookie Value

            if(!check_cookie || check_cookie != '2'){
                var date = new Date();
                var minutes = 60;
                date.setTime(date.getTime() + (minutes * 60 * 1000));
                $.cookie('ga_default', '', {path: '/', expires: -1}); // Expire Cookie
                $.cookie('ga_default', 'bar', {expires: date}); // Set Cookie Expiry Time
                $.cookie('ga_default', '1'); // Set Cookie Value
            }

            if(check_cookie == '1'){
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());
                gtag('config', 'UA-44874885-2');
            }
        });

    });
</script>
    <?php if( $cookieManager->getCookie('ga_default') == 1): ?>
        <script async src="https://www.googletagmanager.com/gtag/js?id=UA-44874885-2"></script>
    <?php endif; ?>
    <?php if($this->getRequest()->getParam('ga') == "1"): ?>
        <script type="text/javascript">
            require([
                'jquery',
                'jquery/jquery.cookie'
            ], function ($) {
                $(document).ready(function(){ 
                    $.cookie('ga_default', '2');   
                });
            });
        </script>
    <?php endif; ?>
<?php endif; ?>
Was this page helpful?
0 / 5 - 0 ratings