Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Google Universal Analytics does not track when Cookie Restriction is enabled #5596

Closed
davefarthing opened this issue Jul 12, 2016 · 32 comments
Closed
Assignees
Labels
bug report Fixed in 2.1.x The issue has been fixed in 2.1 release line Fixed in 2.2.x The issue has been fixed in 2.2 release line Issue: Format is not valid Gate 1 Failed. Automatic verification of issue format is failed Issue: Ready for Work Gate 4. Acknowledged. Issue is added to backlog and ready for development Release Line: 2.1

Comments

@davefarthing
Copy link
Contributor

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

  1. 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: #2518

@EA3HZZ
Copy link

EA3HZZ commented Jul 22, 2016

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

@zolthan
Copy link

zolthan commented Jul 25, 2016

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

A fix would be highly apperciated!

@hostep
Copy link
Contributor

hostep commented Jul 25, 2016

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.

@gewaechshaus
Copy link

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

@vkorotun vkorotun added the SEO label Aug 23, 2016
@bka
Copy link
Contributor

bka commented Sep 1, 2016

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

@ClaudiuCreanga
Copy link

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.

@Dawesign
Copy link

This is still a problem. Any progress?

@i-lean-dev
Copy link

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

@ishakhsuvarov
Copy link
Contributor

Reopening, as fix for 2.1 is not available yet.

@ishakhsuvarov ishakhsuvarov reopened this May 29, 2017
@storepeinture
Copy link

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.

@ishakhsuvarov
Copy link
Contributor

ishakhsuvarov commented Jul 10, 2017

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

@coachdesign
Copy link

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

@ishakhsuvarov
Copy link
Contributor

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

@andidhouse
Copy link

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.

@SchumacherFM
Copy link
Member

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.

@hostep
Copy link
Contributor

hostep commented Jul 24, 2017

@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...

@tommybds
Copy link

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

@magento-team magento-team added Release Line: 2.1 Issue: Ready for Work Gate 4. Acknowledged. Issue is added to backlog and ready for development bug report develop labels Jul 31, 2017
@magento-team
Copy link
Contributor

Internal ticket to track issue progress: MAGETWO-69374

@fvanzani
Copy link

fvanzani commented Sep 6, 2017

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.

@magento-engcom-team magento-engcom-team added Release Line: 2.1 Issue: Ready for Work Gate 4. Acknowledged. Issue is added to backlog and ready for development bug report develop Issue: Format is not valid Gate 1 Failed. Automatic verification of issue format is failed labels Sep 11, 2017
magento-team pushed a commit that referenced this issue Sep 12, 2017
…lue to fix #5596 #10749

 - Merge Pull Request #10749 from hostep/magento2:backport-pr-9713
 - Merged commits:
   1. dc79eb7
   2. 7a611cc
magento-team pushed a commit that referenced this issue Sep 12, 2017
[EngCom] Public Pull Requests - 2.1
 - MAGETWO-72254: Backport PR-9713 for Magento 2.1 - stringify cookie value to fix #5596 #10749
@magento-engcom-team magento-engcom-team added Fixed in 2.1.x The issue has been fixed in 2.1 release line Fixed in 2.2.x The issue has been fixed in 2.2 release line labels Sep 14, 2017
@Gelgersma
Copy link

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

@NickyBass
Copy link

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.

@wescey
Copy link

wescey commented Apr 12, 2018

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?!

@lano-vargas
Copy link

@ 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;

@NickyBass
Copy link

@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.

@Krapulat
Copy link

Krapulat commented Aug 2, 2018

I have the same problem on 2.2.2. Any solution?

@Nexus87UK
Copy link

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?

@tweetyx
Copy link

tweetyx commented Mar 18, 2020

In notice.phtml

helper(\Magento\Cookie\Helper\Cookie::class)->isCookieRestrictionModeEnabled()): ?> getPrivacyPolicyLink()); ?>
<div role="alertdialog"
     tabindex="-1"
     class="message global cookie"
     id="notice-cookie-block"
     style="display: none;">
    <div role="document" class="content" tabindex="0">
        <p>
            <strong><?= $block->escapeHtml(__('We use cookies to make your experience better.')) ?></strong>
            <span><?= $block->escapeHtml(__('To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies.')) ?></span>
  		 
  		<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; ?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug report Fixed in 2.1.x The issue has been fixed in 2.1 release line Fixed in 2.2.x The issue has been fixed in 2.2 release line Issue: Format is not valid Gate 1 Failed. Automatic verification of issue format is failed Issue: Ready for Work Gate 4. Acknowledged. Issue is added to backlog and ready for development Release Line: 2.1
Projects
None yet
Development

No branches or pull requests