Develop and test code for Google Analytics on localhost

Sometimes you may need to develop custom tracking code for Google Analytics. If you sit in front of your development machine and the development or testing site you are using is localhost you will run into the problem that you don't see a tracking event firing to Google.

So you may ask you how to test the code without going into production? There are several options...

  1. Run your development website on a public/internal test domain.
  2. Add some hostnames to your local "hosts" file.
    1. Add below _setDomainName line to your ga.js tracking code:
      var _gaq = _gaq || [];
      _gaq.push(["_setAccount", "UA-1234-1"]);
      _gaq.push(["_setDomainName", "none"]);
      _gaq.push(["_trackPageview"]);
    2. Add cookieDomain to your Analytics.js tracking code:
      ga("create", "UA-1234-1", {"cookieDomain":"none"});
      ga("send", "pageview");
    3. If gtag.js API detects that you're running a server locally (e.g. localhost), it automatically sets the cookie_domain to 'none'.

Personally I prefer to use #3 variants as it may be the easiest to add - at least in Drupal with the Google Analytics module as I do not need to maintain the hosts file that may collide with DNS services. Some users may also work on locked down PC's and have no permission to alter the global company DNS server configuration or their local hosts file.

Now you will see the hits to Google's __utm.gif.

Rating
Average: 7.7 (68 votes)