简体   繁体   中英

How to change cookie domain in google analytics & google tag manager

The below two group of codes creates a few cookies, one is google tag manager and other is google analytics code. I want to change the cookie domain to be www.example.com in each of those instead of .example.com or .www.example.com.

<!-- GTM dataLayer -->
    <script>
        dataLayer = [];
        dataLayer.push({
        });
    </script>
<!-- End of GTM dataLayer -->

<!-- Google Tag Manager -->
    <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-XXXXXX');
    </script>
 <!-- End Google Tag Manager -->

And

    <script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
        })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

        ga('create', 'UA-xxxxxx', 'auto');
        ga('send', 'pageview');
</script>

GTM does not create cookies by itself. If you have custom tags in GTM that create cookies you need to contact the respective vendors (however not all marketing tags allow for this).

The cookie domain in Google Analytics can be set either as parameter or via the configuration object. Ie for analytics.js you either replace "auto" with your cookie domain

  ga('create', 'UA-xxxxxx', 'www.domain.com');

or you provide a configuration object with the relevant key/value pair:

ga('create', 'UA-xxxxxx',{
'cookieDomain':'www.domain.com',
});

And while you haven't asked for it, in the "new" (actually by now the current) tracking code via the gtag.js library the cookie domain is set in the config call (which also sends the pageview):

gtag('config', 'GA_TRACKING_ID', {
  'cookie_domain': 'www.domain.com',
});

And if you have configured GA via a GTM tag you can go to the "fields to set" option in "more settings", click "add new field", enter "cookieDomain" as field name and your domain as value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM