How to use Google Analytics and Google Tag Manager 2 on a local address?

I'm relatively new to GTM and have been experimenting with the new interface which will be fully replacing the original on 1 April: https://support.google.com/tagmanager/answer/4605576.

However, I have encountered some issues getting Google Analytics to register pageviews when testing on a local address. There is a solution for this using the original GTM layout outlined here: Track localhost on Analytics in Google Tag Manager, so I don't wish to ask a duplicate question. However, in the new Google Tag Manager design there is no longer an option to set Cookie Domain to 'none', so how could I now test Google Analytics and GTM from a local address?


If you go to "fields to set", click on "add new field" and start typing into the "field name" input box the autosuggest function will suggest applicable field names (ie if you start typing "coo" it will suggest everything related to cookies, including the cookie domain).

"Behind the scenes" GTM has always used the "set fields" mechanism of GA, this has now been made explicit in the interface. But this does make a difference to the way GA tracking works, so simply "set field"->"cookieDomain" to "none" and everything will work like before.


Rather than modifying your tags to add/remove cookieDomain when moving between localhost and yourdomain.com I do the following to set cookieDomain automatically based on hostname.

  • Create a custom JS variable that will be used to set the value of cookieDomain.
  • Variable Name: XYZ-JS-CookieDomain (or whatever your naming convention is)
  • Type: Custom JavaScript
  • Code (the debug stuff is how I do all my custom JS variables, it's not required):

    function() {
        var result = {{Page Hostname}} == 'localhost'
                     ? 'none'
                     : 'auto';
    
        if ({{Debug Mode}}) {
            console.warn('XYZ-JS-CookieDomain', result);
        }
    
        return result;
     }
    
  • Configure the Tag.
  • More Settings > Fields To Set
  • Field Name: cookieDomain
  • Value: {{XYZ-JS-CookieDomain}}
  • Now when you run from localhost cookieDomain will be set to "none" and anywhere else it'll be "auto".


    I guess you don't need to do any of these things now. cookieDomain is set to "auto" by default. 在这里输入图像描述

    链接地址: http://www.djcxy.com/p/81326.html

    上一篇: 如何通过GA的新analytics.js设置自定义变量

    下一篇: 如何在本地地址上使用Google Analytics和Google跟踪代码管理器2?