20+ Google Analytics Tag Manager (GTM) Tips

Google Analytics Tag Manager

How to use Google Analytics Tag Manager 2019: 90+ New Google Analytics Hacks 

This blog explains the 90+ New Google Analytics Hacks for testing and publishing Google analytics Tag Manager


Just like your content management system manages the content of your website—by allowing you to insert text, headings, and images in a web-based interface—a tag management system manages the tags—allowing you to insert those bits of JavaScript, such as the Google Analytics tracking code.


It offers a web-based interface to choose, edit, and manage those tags when they are included in your web pages.


This approach offers a number of advantages:

  • There’s no need to make changes to the actual source code of the site or its templates when updating or adding tags.
  • You can keep track of and organize tags to avoid duplication and mistakes.
  • There are built-in debugging, testing, and preview tools.
  • You can use version control to keep track of changes.


There are multiple levels of permissions to view, edit, and publish tags.

Tag management tools separate the process of adding and updating tracking tags from the process of altering your site’s templates and code. There are a number of good tag management tools available.


But this blog focuses on Google Tag Manager (GTM) since it’s a free tool that works very well with Google Analytics. (And if you’re a Google Analytics Premium subscriber, Google Tag Manager is also covered by the service-level agreement for Google Analytics Premium.)


Testing Your Implementation


Preview and Debug Mode

You can enter GTM’s Preview mode by selecting the drop-down on the Publish button in the top-right corner and then choose Preview.


You’ll see a banner indicating that you are in Preview mode in the container overview. Behind the scenes, Google Tag Manager has set a cookie so that only your web browser will receive the new tags, triggers, and variables you’ve set up, while all other visitors to the site continue to get the previously published version.


You can now visit your website to see what the Google Tag Manager is doing. GTM’s Preview mode adds a debug panel at the bottom of the page when loading the site; it includes information about which tags fired (and didn’t) for the page.


Note  Some types of ad-blocking software may prevent GTM’s debug panel from loading. If you don’t see the debug panel after entering Preview mode, disable these tools in your browser for your website and try again. 


You can click a tag to see more information about its properties that were filled in by Google Tag Manager and the triggers that caused it to fire.


Note  You can also see the value of variables and messages pushed to the data layer for the page with the additional tabs at the top of the debug panel. 


Every time you make changes in Google Tag Manager, before publishing you should use Preview mode to inspect the changes and to make sure that your tags are firing when you expect them to (and not when you don’t). Remember, Preview mode only affects what you see in your browser, not what others who visit your website see.


If you make changes to Google Tag Manager while in Preview mode (such as altering a tag or trigger), select Refresh to update your site. You can exit Preview mode at any time by selecting Leave Preview Mode. Both of these options are found in the Preview mode banner at the top of Google Tag Manager.


Beyond GTM’s debug panel, there are a number of additional browser tools that can be useful for seeing the Google Tag Manager and Google Analytics code that is included on the page, which you’ll take a look at later in the blog.


Google Tag Manager DEVELOPMENT

Google Tag Manager AND DEVELOPMENT

Beyond the testing enabled by Preview mode in Google Tag Manager, you may have additional processes already in place for testing updates to your site, through development, test, or staging versions of the site.


In some cases, Google Tag Manager allows you to skip this process and simply use GTM’s preview tools since you can deploy changes in Google Tag Manager without requiring changes to the source code of your site.


For changes and additions in Google Tag Manager that accompany changes to the content of the site itself, however, you will want to ensure that everything is working on these test sites before they are put into production through your normal processes.


Whatever your current testing setup, GTM’s preview tools provide you with an additional layer of assurance that code will work correctly when published to your live production site.


All these tools only work if you use them, however. Don’t skip straight to the publish button and use Google Tag Manager as a way to avoid testing. Thorough testing ensures accurate measurements in Google Analytics and other analytics tools, and more importantly, a website that doesn’t malfunction for users.


Troubleshooting Tools for Google Analytics

Troubleshooting Tools for Google Analytics

GTM’s debug panel (described in the previous sections) is useful for understanding which tags fired when in Google Tag Manager, including tags for Google Analytics.


Sometimes, however, you want to know exactly what information was sent to Google Analytics, either for published or previewed versions of your Google Tag Manager container.


The following sections provide suggestions for a variety of tools that can assist you in delving into how your tags work. The focus is primarily on the Chrome browser since there are several tools available from Google specifically for Chrome, but comparable functionality is available in all browsers, and options for other browsers are also discussed.


[Note: You can free download the complete Office 365 and Office 2019 com setup Guide for here]


Viewing Google Analytics Debug Information

Viewing Google Analytics Debug Information

Once Google Analytics debug mode is enabled by either of these two methods, you can view information on what data Google Analytics collected and sent by using the JavaScript console.


In Chrome, you can access the console via the Chrome menu under More Tools ➤ JavaScript Console. 


In other browsers, check your documentation for menu items or keyboard shortcuts to access the JavaScript console.


The console contains JavaScript errors, warnings, and messages. GA’s debug mode prints several messages about the commands executed by Google Analytics.


The “Sent beacon” message indicates that Google Analytics has sent a tracking hit upon the execution of a send command. Below that message is a breakdown of the data included in the hit. This serves as your confirmation of any data that was sent to Google Analytics from the Google Analytics tag(s) included in Google Tag Manager.


Other Browser Tools

Apart from the tools specifically for Google Tag Manager and Google Analytics described in previous sections, browsers include a number of general-purpose web development tools that can be useful to view the Google Analytics and Google Tag Manager scripts included in a page, the Google Analytics cookies, and the Google Analytics tracking hits generated.


In Chrome, beside the Console tab, the Developer Tools also include a browsable tree of the HTML document, a list of scripts included and cookies set for the current page (the Resources tab), and a list of outgoing requests from the browser window and the responses received (including the Google Analytics tracking hit, in the Network tab).


Internet Explorer, Firefox, and Safari all contain developer tools that are similar to Chromes. Check your browser’s documentation for menu items and keyboard shortcuts to access these tools.


Google Analytics Real-Time Reports

Google Analytics Real-Time Reports

Google Tag Manager and Google Analytics APIs

Interfacing with an API generally requires facility in a programming or scripting languages, such as Java or Python, although there are a number of lightweight possibilities (HTML and JavaScript solutions with the Embed API, for example) for less-proficient developers.


This appendix provides an overview of the available APIs and discusses how they can be used, but it does not contain in-depth examples of programming using these APIs. There is extensive documentation and sample code available, and helpful tools if you’d like to explore further.


There is also an existing ecosystem of third-party products, both free and paid, that make use of these APIs. You can find a directory of products that integrate with GA and GTM in the GA partner apps gallery.


Google API Basics


Google provides APIs for many of its products. Most of these APIs share a common infrastructure and design pattern. Some of the common features include the following:


Authorization: Google uses OAuth authorization to provide access to your accounts (equivalent to signing in with your email and password on the website).


OAuth provides functionality both for client-side authentication (for scenarios where the user has the appropriate level of access and logs into the product) and for server-side authentication (for scenarios such as automated dashboard updates, scheduled data pipelines, etc.).


Client libraries: The APIs are REST APIs and can be accessed via HTTP by any method. However, official client libraries are available in a number of languages. Coverage varies by API and language. Typically, Java and Python have the most complete libraries and documentation.


Quotas: The APIs have quotas on the number of requests that can be made in a given time period. You can manage your quota usage through the Google API Console.3 Quota adjustments can be requested if needed for a particular application.


With the Google APIs on a common infrastructure, integrations between GA/GTM and other Google tools—such as Google Sheets and Google Cloud Platform—are simplified.


Although the APIs work from any tool or environment, it is common to use multiple Google-provided tools and systems, where appropriate, to achieve your ends with a minimum of bolting components together.


Google Tag Manager API


The GTM API accesses and updates tags, triggers, and variables. As such, it’s the basis for convenience tools for setting up containers without using the web interface: making copies of containers, performing automated changes across many containers, and so forth.


Remember, GTM doesn’t contain any data; it only enables it to be sent to other tools (like GA), so GTM’s APIs are focused entirely on configuration.


GTM’s API can do all the same things that we can do in the web interface: create accounts and containers; assign permissions; set up tags, triggers, and variables; and publish and manage versions.


Real-Time Reporting API

Real-Time Reporting API


The Real-Time API allows access to the data available in the real-time reports in GA, including pages, events, goal conversions, geographic locations, and traffic sources. This is a more limited set of data that is available in the Core Reporting API, but unlike that data, it is available in real time.


Accessing this data programmatically enables the possibility of real-time dashboarding or alerting. Dimensions and metrics in the Real-Time Reporting API use the rt: prefix.


Embed API

The Embed API is a set of JavaScript functions that provide a wrapper of additional features around the Core Reporting API. It includes a set of components to easily accomplish the following:

  • Authorize a user and select f
  • From available accounts, properties, and views.
  • Run queries against the Core Reporting API.
  • Chart the results using Google Charts.


The Embed API is a good starting point if you’re just beginning to explore the GA reporting APIs because it uses JavaScript, it is easily tested and iterated in a web browser, it handles the heavy lifting with OAuth, and it provides built-in visualization capabilities for the data.


Design Patterns for Events in Google Tag Manager

Design Patterns for Events in Google Tag Manager



The first challenge is to trigger the tag at the appropriate time: usually, when the user clicks something in the page in the browser. Fortunately, JavaScript allows you to call a function when almost any user action occurs within the page.


Browsers use a convention called the Document Object Model (DOM) to represent the content of the page and to allow JavaScript to interact with that content.


The DOM allows you to access a certain element of the page (a link, button, form field, etc.) and to call a JavaScript function when a certain event happens (clicking the link, entering text in the form field).


The DOM includes events for mouse interactions, keyboard interactions, and more. Most typically, you'll be interested in a click, but you'll see examples of other kinds of interactions as well.


The simplest possible example of calling JavaScript on a click might look like this:

<a id="link1" href="/some/link" onclick="someFunction();">Click me</a>

You can call a JavaScript function using attributes on the element in question. In this case, someFunction() is called when a user clicks on this link. You can also add a click event to an element with an event listener, which is a function you add elsewhere in the page targeting that element by its id, position in the DOM, or other attributes.


document.getElementById('link1').addEventListener('click', someFunction);



Google Tag Manager uses the DOM and its events in its built-in auto-event tracking. Google Analyticsining an understanding of the DOM will be useful if you need to expand beyond the capabilities of GTM’s auto-event tracking with custom JavaScript.


Several of the examples in this blog use these techniques, and working with the DOM through JavaScript is a useful skill for you to develop to extend and adapt these examples.


Design Pattern 1: GTM’s Auto-Event Tracking

GTM’s Auto-Event Tracking


For clicks, Google Tag Manager provides a number of variables:

The {{Click Element}} variable returns the entire HTML object that was clicked from the DOM, including all its attributes.
  • {{Click Classes}} and {{Click ID}} return the values of the class and id attributes (if any) on the element.
  • {{Click URL}} includes the destination of a link element (the href attribute).
  • {{Click Target}} includes the value of the target attribute (for example, target="_blank" to open the link in a new window/tab).
  • {{Click Text}} includes the text content of the element.


Suppose the following link were clicked. <a id="link1" class="button" href="Example Domain" target="_blank">Click me!</a>





All Elements and Just Links Target Types

Why does Google Tag Manager treat these differently? Opening a link typically replaces the current page in the browser window, which means that any JavaScript executing in the current page is interrupted.


(This is not a problem for links that load in a separate window or that merely trigger a tab, modal popup or other content within the same page, but it does affect any content that replaces the current page in the same browser window, including links to web pages or PDFs, for example.)


The interruption of JavaScript could mean that as the destination page of the link begins to load, your tracking tags are prevented from executing. In order to work around this, Link Click triggers give an additional option to delay the link until the tags have finished or a short maximum time elapses


For clicks on links, there’s also the ability to limit the pages on which the listener is active. Since the “Just Links” option can temporarily interrupt other actions that result from clicking the link, you should be extra careful about testing before publishing to ensure that this behavior doesn’t affect the functionality of your website.


This option allows you to restrict the trigger to only pages where it is needed and thoroughly tested.


The Mechanics of Auto-Event Tracking

What Google Tag Manager actually does for these auto-event tracking triggers is quite simple. It adds event listeners to the DOM and, when the event occurs, it does a dataLayer.push with a number of related pieces of information it uses to populate the variables described earlier.

Here’s an example of what a data layer message for a Google Tag Manager auto-event looks like:

'event': 'Google Tag Manager.click',
'Google Tag Manager.element': http://thesisscientist.com,
'Google Tag Manager.elementClasses': 'button',
'Google Tag Manager.elementId': 'link1',
'Google Tag Manager.elementUrl': 'http://thesisscientist.com',
'Google Tag Manager.elementTarget': '_blank' }


GTM’s event names and properties are all prefixed with Google Tag Manager to keep them separate from any events you may push to the data layer and prevent naming collisions.


They are all string values, except for Google Tag Manager element, which contains the entire HTML object that was clicked. Just like any other data layer message, you can see these in GTM’s debug pane while in preview mode.



If you’re already a developer familiar with JavaScript, this design pattern is right up your alley. It allows you all the flexibility of including custom JavaScript, with the advantages of versioning and testing in Google Tag Manager. Here are a few recommendations.


For code you include in Google Tag Manager, follow JavaScript best practices such as wrapping scripts in Custom HTML tags in anonymous functions and checking for the existence of variables (such as dataLayer) before using them. Such practices are an especially good idea to avoid conflicts if several independent developers may be adding JavaScript to the site.


Also, remember to rely on Google Tag Manager features rather than reinventing or obscuring them with JavaScript.


For example, use the built-in click listeners rather than attaching events with addEventListener(), and to give your triggers clarity use the Google Tag Manager.js or Google Tag Manager. dom events, rather than code in a tag that uses window.onload or other methods.


Applications of Interaction Tracking

Given the three design patterns you’ve laid out, you can now take a look at some specific applications of tracking in Google Tag Manager. As a guiding principle, you’ll stick to GTM’s auto-event tracking (design pattern 1) and use custom JavaScript within Google Tag Manager for cases not covered by auto-event tracking (design pattern 2).


The third design pattern always exists as a fallback should you need it, but the examples in this blog will avoid it in favor of solutions that centralize tracking code in Google Tag Manager and do not rely on adding code to your site.


Outbound Links

Let’s start with one of the simplest and most common scenarios for tracking events in Google Analytics: recording clicks on links to other websites.


Such links could range from merely informational links to articles or content hosted on other websites, to important affiliate links, or to channel traffic to third parties with whom you have a relationship. In any of these situations, you might want to know who clicks on which links, and how often.


This scenario is a perfect application for your first design pattern: using GTM’s auto-event tracking since this is a straightforward use of tracking clicks on links.


Note Google Analytics’s pageview tracking already allows you to see the order of pages within your site that a user viewed during the session, so you don’t need to use events to track internal links, unless you want to pay special attention to certain links (such as a particular promotional link, or a link in a particular position in dynamically rotating content, for example).


You can use the Click URL variable in the trigger to target only links that point to other sites. Although you can use the whole click URL (which includes the full URL.


e.g., http://thesisscientist.com/ directions?location=wonderland), it would be handy to have a variable that has just the hostname (e.g., thesisscientist.com). You can do this by setting up an additional variable. Let’s walk through the whole process.


PDFs and Other Downloads

Another common type of link to track is any link to a downloadable file (PDFs, most commonly, but a link to any file that isn’t a web page can also be tracked).


The process for tracking downloads will be similar to the outbound link tracking in the previous section. The Click URL variable you used would contain the file name of the linked file, and you could use some conditions based on this variable to trigger your tag (probably using a regular expression). 


However, it might be handy for you to pull out just the file extension (so you can check if it’s a web page or a download). You can create a variable to do exactly that. Here’s the process.


This very elegant function was first proposed by Stephane Hamel on the Google Tag Manager Google+ community.

Select the Continue button to specify a trigger for the tag.

  • Choose Click, and then select the New button to create a new click trigger.
  • Choose Just Links as the target type (which accounts for tracking of links that open in the same browser window; see earlier in the blog for a discussion of the difference between All Elements and Just Links triggers). Choose the Wait for Tags option with the default two-second maximum.


Select the Continue button to filter pages on which the trigger is enabled if needed. If you want to restrict this trigger to only listening for download links on certain pages, you can use a condition or regular expression to match certain pages. To listen on all pages, use a regular expression to match any URL:

  • {{Page URL}} – matches RegEx – .*
  • Select the Continue button to choose the firing conditions. Choose Some Clicks.
  • Select the {{Click URL File Type}} variable you created from the drop-down, and the criteria to match.


You could just use “contains pdf” (for example), but then you‘d need to create a separate trigger for each different type of file you‘re interested in.


Instead, let‘s use a regular expression (see the screenshot below):

  • {{Click URL File Type}} – matches RegEx (ignore case) – pdf|doc|xls|zip
  • Feel free to extend this regular expression to take into account other types of files on your site. Alternatively, if you want to track anything that isn’t a web page, a trigger like this one would work:
  • {{Click URL File Type}} – does not contain – html
  • Note that this will track any non-HTML link, including images.
  • Select the Create Trigger button, giving the trigger a name: “Click – Download Links”. Google Tag Manager saves the trigger and returns to creating the tag.
  • Save the tag, giving it a name: “GA – Event – Downloads”.



If you’re paying close attention, you’ll notice that this code doesn’t really track downloads, it tracks clicks on downloads, which is a subtle but important distinction. What happens if someone lands directly on a PDF from a link from another website (like a search engine, for example), without going through one of your web pages?


Since you can’t include JavaScript in PDFs or other files, they’re not directly measurable with Google Analytics, Google Tag Manager, and JavaScript.


However, you could use server-side code to intercept a direct request for a PDF, send data to Google Analytics, and then seamlessly redirect the user to the PDF file. This is a perfect application for Google Analytics’s Measurement Protocol.


Mail and Phone Links

It’s possible to include links that launch a new email or dial a phone number by using link URLs like the following:

<a href="mailto:madhatter@thesisscientist.com">Send me email!</a> <a href="tel:14125550000">(412) 555-0000</a>


Tabs, Hover, Scroll, and Other Content Interactions

There are many additional ways that users can interact with the content of the pages on your website. In this section, you’ll look at a variety of examples of measuring engagement with page content.


Tabs and Other In-Page Content

Tabs, accordions, and other ways of showing and hiding content on the page are typically interacted with by clicking an element that you can use a click trigger to listen for. Ideally, the tabs or accordion links have a class or is that you can leverage in your trigger criteria to select the correct elements.

<p class="tab">
<span class="tab-title">Tweedle Dee</span>
<p class="tab-content">...</p>
<p class="tab">
<span class="tab-title">Tweedle Dum</span>
<p class="tab-content">...</p>


You can see how to use the auto-event listeners that were already discussed with filters such as the following: {{Click Classes}} – contains – tab-title. What if you don’t have nice neat class or id attributes on the items you’d like to track, however?

Recall that in addition to the variables like {{Click Classes}} and {{Click ID}}, there is also the {{Click Element}}, which contains a reference to the DOM for the element that was clicked.


Google Tag Manager provides the option to match by a CSS selector, which allows us to specify a hierarchy of elements, classes, or id attributes to target. 


Keep in mind that this approach can be fragile and broken by the arrangement of elements on the page changing, so it should be used carefully and only when other methods are insufficient.


Note Similar to tabs or other in-page content, a related issue is pages using AJAX, where a complex sequence of interactions may occur within a single page—an entire checkout or registration process.


For example—without the page reloading. In cases like this, you may actually wish to record additional pageviews to Google Analytics in order to separate and track the process.


Time Spent

GA calculates metrics like Time on Page and Session Duration in a very simple way: it simply subtracts the timestamp of one page from the next page the user views.


This isn’t a perfect measure by any means. For example, what about the last page the user views? They might have spent 10 seconds or 10 minutes, but you don’t really know. Since there isn’t a subsequent timestamp to subtract it from, it doesn’t have a time on page and isn’t included in the session duration.


Google Tag Manager includes Timer triggers that allow you to trigger an event every so often, which is a simple way for you to get a more accurate picture of how much time users spend on pages.



  • Create a new tag. Choose Google Analytics ➤ Universal Analytics as the type.
  • Use your previously created {{GA Property ID}} variable for the Tracking ID.
  • Select Track Type ➤ Event.


Fill in the Category, Action, and Label to be sent to Google Analytics. You’ll want to choose your own conventions for how you’d like to see these in your reports, but one sensible choice might be:

  • Category: Time Spent
  • Action: 30-second interval
  • Select the Continue button to specify a trigger for the tag.
  • Choose More, and then select the New button to create a new trigger.
  • Choose Timer as the event to cause the trigger.


Keep Google Tag Manager.timer as the event name. (Notice that you could have multiple “stopwatches” running with different names, on different cycles or to time different things, but let’s assume for now this is the only one.) 


As the interval, let’s use 30000 (that’s milliseconds, so 30 seconds). And for the limit, let’s say 60 times (so it will stop counting after 30 minutes if the user is still on that same page).


Note Have some care about how rapid your timers are, and set a limit on them. Google Analytics has a limit of 500 hits per session, so let’s not fire an event every second!


Select the Continue button to filter pages on which the trigger has the timer count on (if needed). If you want to restrict this trigger to only timing certain pages, you can use a condition or regular expression to match certain pages. To use the timer on all pages, use a regular expression to match any URL:

{{Page URL}} – matches RegEx – .*
Select the Continue button to choose the firing conditions. Choose All Timers.
Select the Create Trigger button, giving the trigger a name: “Timer – 30s”.
Google Tag Manager saves the trigger and returns to creating the tag.
Save the tag, giving it a name: “GA – Event – Time Spent”.


Caution Please note that implementing these timer events will have a significant impact on time-based metrics in Google Analytics (Time on Page, Session Duration) as well as the Bounce Rate metric. You should be prepared for this, and make a conscious decision about how much time on a page you want to be considered “not a bounce” for a user.


You could go even further in measuring the time the user is truly engaged with the content, by checking things such as whether the tab is active, how far down the page they’ve scrolled, and so on. See the next section for an example using scrolling.


For the trigger for the tag, select All Pages. (Alternatively, if you only wish to track scrolling on some pages of your site, you could specify a more restrictive trigger here.)

Save the tag, giving it a name: “Listener – Scroll Events”.


You don’t necessarily need to understand all the details of this script to use it, but in a nutshell what it does is this: it allows us to set some breakpoints (by percentages or pixels) in a configuration object (the bolded section at the end of the code).


And then monitors for scrolling activity and sends a message to the data layer when those breakpoints are reached (which you can see in the earlier bolded section). A few smart things this script includes are the following:


Careful cross-browser support so that it functions across the widest variety of browsers and versions.


A cache that captures whether each of the events has previously been sent (so that there’s only one 25% scroll event for the page, for example). A timer that throttles how often the scroll position is checked (in this case at most every 500 milliseconds) so that you’re not running your function every time the screen moves one pixel.


These are good concepts to incorporate in any custom event listeners you create.

Next, let’s create a variable for the distance data layer property.

Create a new variable.
For the variable type, choose Data Layer Variable.
For the Data Layer variable name, enter attribute.distance (which corresponds to the name in the preceding code).
Save the variable, giving it a name: “Scroll Progress”.
Finally, create a tag to send this data as events to Google Analytics.


Hover and Other Interactions


When a user clicks on an element, GTM’s auto-event tracking can be used. JavaScript additionally supports other types of interactions, such as mouseover (that is, moving one’s mouse over an element so that you could track hovering that doesn’t necessarily result in a click), change (for entering text or changing a selection in a form element), and many others as well.


These aren’t built into GTM’s auto-event tracking, but you can build on the model with custom JavaScript to track these interactions using Google Tag Manager.


Extending GTM’s Auto-Event Tracking Model

A sensible way to model the data for an interaction like hovering would be to parallel the same pieces of data. Google Tag Manager captures for a click. You might use the following data layer message to indicate a mouseover:


'event': 'mouseover',
'Google Tag Manager.element': http://thesisscientist.com,
'Google Tag Manager.elementClasses': 'button',
'Google Tag Manager.elementId': 'link1',
'Google Tag Manager.elementUrl': 'http://thesisscientist.com',
'Google Tag Manager.elementTarget': '_blank' }


Look familiar? It’s just like the data layer message that GTM’s auto-event tracking creates for a click, except the name of the event is mouseover instead of Google Tag Manager.click.


This lets you use the same set of familiar variables to set up your event tags. The only thing you’ll need to add is a tag that generates this message to the data layer when the desired interaction occurs.


To do that, you’ll need to write some of your own JavaScript; consult the sidebar earlier in the blog for resources. The add Event and sendAnalyticsEvent functions in the scroll tracking code in the previous section are also a good foundational example for extending to your own event listeners.


Social Interactions


Another common type of interaction within a page is a social action: the now nearly ubiquitous “Like This” and “Tweet This” buttons (and every other social network you can think of).


Although you could measure these with event tracking in Google Analytics, Google Analytics actually has a separate, specific hit type specifically designed to capture information particular to social interactions, with its own report (in the Acquisition ➤ Social ➤ Plug-ins report in Google Analytics, where it is brought together with other data about social traffic to your website).


The Google Analytics code for tracking a social interaction is very similar to event tracking:

ga('send', 'social', 'network', 'action', 'target');


Instead of an event’s category, action, and label, social interaction has a network, action, and target:

  • The network is the social network (Facebook, Twitter, etc.)
  • The action is what the user did (like, unlike, follow, tweet, retweet, etc.)
  • The target is the thing that is being liked or tweeted, usually a URL (and often simply the URL of the current page)


Credit to Doug Hall at Conversion Works for first suggesting this pattern. Of course, Google Tag Manager has a tag that generates the Google Analytics code for you, just like for events, where you can fill in the network, action, and target with variables.


Social Actions: Initiation vs. Completion

Based on the examples that you’ve already seen in this blog, it would be easy enough to set up a Google Analytics social tag with a click trigger for a Tweet button (for example).


The challenge, though, is that clicking the Tweet button may only be the first step of several: first, if the user isn’t already logged in, Twitter will prompt her to do so, and then the user may edit the tweet before finally publishing it.


The click that initiates the process, then, may not really be what you would like to capture, but rather the successful completion of the tweet. (And an additional wrinkle may be that the button exists in an iFrame element, which presents additional challenges to directly track the click.)


Your page and its code don’t have direct access to the user’s Twitter activity (for obvious security and privacy reasons). As a result, to measure completion of the social action, you typically have to interface with an API for the social network in question.


 Twitter’s API also provides for a callback function when certain events occur (such as a tweet, retweet, etc.).


Facebook has similar functionality for likes (and unlikes). Let’s take a look at a specific example for Facebook here; you can extend this model for other social interactions using this basic structure, although the particulars will depend on the social network and what APIs it provides.





Another common type of interaction within a page is with embedded media, often a video that’s included in a page. Like social network buttons, each video platform has its own player with unique implementation details. Let’s take a look at YouTube, the most common video player.


By now you’ll be familiar with the basic pattern of this code: first, a custom JavaScript listener tag (using the YouTube API), and then a Google Analytics event tracking tag to send the data to Google Analytics. Again, let’s dispense with the step-by-step instructions and cut right to the chase.



Google Analytics has two hit types, event and social, for tracking interactions within pages. Google Tag Manager has built-in tags for each of them.


Events are used for general interactions with page content, including such examples as download links, outbound links, tabs and accordions, video plays, and more. Social interactions are used for social network actions, such as liking a page on Facebook or tweeting it on Twitter.


The challenge for tracking interactions in Google Tag Manager is selecting the appropriate triggers for the interaction and the appropriate variables to capture data about them. There are three basic approaches:


Using GTM’s auto-event tracking, which has built-in capabilities to track clicks on items within the page (as well as a few other scenarios, such as forms and timers). 


Using custom extensions to GTM’s capabilities with Custom HTML tags and Custom JavaScript variables. Knowledge of JavaScript and the DOM are especially useful in being able to create scripts to listen for custom events and extract information from the page.


Using JavaScript on the page to send data to Google Tag Manager, which is a flexible, developer-friendly method, but it keeps management of this code outside GTM’s control. 


Interaction events are represented as messages in GTM’s data layer. You can use these messages to create triggers and populate variables for your interaction tracking tags.


Google Analytics Tracking events and Links and Google Analytics E-commerce

Enhanced E-commerce offers expanded tracking of users’ interactions with products all through the site, from viewing a product in a list, adding it to the cart, and ultimately purchasing.


It offers richer ways to categorize and track all types of product interactions. Because of this, you will generally have to make tracking changes throughout much of the website to take full advantage of enhanced E-commerce.


Which should you choose? If you need only very simple E-commerce tracking, the basic option may suffice. For many sites, the enhanced E-commerce offers much deeper and more actionable data, however, so if you have the resources to implement it, it’s recommended.


With either E-commerce tracking option, implementation generally involves two sets of tasks:

  1. Changes to your website to provide the E-commerce data to Google Tag Manager via the data layer.
  2. Changes to tags in Google Tag Manager to accommodate sending E-commerce data to Google Analytics.


This blog lays out the process for both basic and enhanced E-commerceincluding walking through any Google Tag Manager changes (the second item). For the first item, the information that needs to be present in the data layer and in what format will be detailed.


This is normally accomplished by server-side changes to the website to provide this data in the data layer, and so the specific implementation will depend on your site and E-commerce platform.


E-commerce TRACKING FOR NON-E-commerce sites

Although it’s generally intended for measuring purchases, GA’s E-commerce tracking features are well-suited to any type of transactional interactions, whether there’s a monetary component or not. This might include scenarios such as the following:


Selecting from a catalog or library of items, such as e-blogs, videosor other content, and downloading, checking out, or viewing such items.

  • Registering for classes or online courses.
  • Applying for volunteer or job opportunities.
  • Selecting or configuring products that are ultimately purchased offline (such as a car).


  • In many cases, you might find goals sufficient for measuring these scenarios. If you want more detailed data about the particulars of each transaction, however, E-commerce tracking can be a good option. All of the E-commerce tracking functionality described in this blog will still work even with $0.00 amounts.


The remainder of this blog is divided into two sections, for basic E-commerce and enhanced E-commerce tracking. For implementation, you should choose one option or the other, and it’s only necessary to read the relevant section.


Basic E-commerce Tracking

E-commerce Data in the Data Layer

Data about the purchase will be provided on the final confirmation page of the purchase process using Google Tag Manager’s dataLayer object. Google Tag Manager specifies a format and labeling for the pieces of information Google Analytics requires.


Here’s an example of purchase data in the data layer; let’s break down the pieces afterward.

dataLayer=[{transactionId:"AW699168",transactionAffiliation:"ThesisScientist",transactionTotal:42.98,transactionTax:3,transactionShipping:3.99,transactionProducts:[{sku:"MH342",name:"Thesis",category:"Hats",price:17.99,quantity:1},{sku:"MH007",name:"Purple blogs",category:"Hats",price:24.99,quantity:1}]}];</script>


Caution  You should only declare the data layer (with a statement like dataLayer = []) once within the page, and it should be before the Google Tag Manager code. Declaring the data layer again at a later time will overwrite its previous values and can cause Google Tag Manager to behave unexpectedly. 


To provide additional values to the data layer after it’s been created, use dataLayer.push(), which appends to the data layer, rather than overwriting it.


In this case, you need the values to be included when the page loads, so you’ll include the E-commerce data in the declaration.

This code should be included only when the transaction is completed—that is, on the final receipt page in the checkout process.

  • The first set of attributes summarizes the transaction:
  •  the transaction is required and serves as a unique identifier for this particular purchase.
  •  transactionAffiliation is optional and could denote a particular store (if you have multiple stores) or affiliate code.


  • TransactionTotal is required and represents the total revenue for the transaction. (This total can be inclusive or exclusive of shipping and tax, depending on how you want to see revenue in your reports.)
  • transaction tax and transactionShipping are optional and represent tax and shipping charges for the transaction.


The next part of the E-commerce data is an array called transaction products. The array has entries for each of the distinct products purchased. Each product entry contains the following attributes:


  • SKU and name are required and represent an identifier and a label for the product.
  • the category is optional and represents a categorization or grouping of products.
  •  price is required and represents the unit price for the product.
  •  quantity is required and represents the number of units purchased. It should be an integer.


You need to repeat this information in the data layer for each of the products that are part of the transaction. In our example, there are two products.


As mentioned previously, the values of the information in the data layer are included from your site’s data, typically using server-side code to pull the values from your database or E-commerce platform.


The specifics of how to do this are particular to your site and the tools you are using to process these transactions, but as long as you format the data in this way, Google Tag Manager and Google Analytics can use it.


Caution  Since you’re inserting values from your database into this JavaScript code, you need to be careful about formatting and syntax. Specifically, beware of apostrophes or quotation marks in text fields (note the apostrophe escaped using the backslash in 'ThesisScientist' in the example code).


Also, note that currency values are numeric, and so should contain only digits and a decimal (no currency symbols or commas) — so 1342.57, not $1,342.57.


Create a Goal in Google Analytics for the Checkout Process


The tasks in the previous sections are the only things you need to do to enable E-commerce reporting in Google Analytics and collect data on transactions.


However, you probably also want to set up a goal with a funnel for the checkout process so that you can see how users progress through the steps leading up to their completed purchase (or fail to complete that process). 


Enhanced E-commerce Tracking

The enhanced E-commerce features in Google Analytics go beyond just measuring completed purchases, to track E-commerce interaction activity throughout the entire website. 


The data you can collect include interactions of two types: with products (from viewing the product all the way through purchase) and with internal promotions (such as a banner or other offer).


Information about all of these interactions will be handled by adding information to the data layer. Google Tag Manager and Google Analytics expect a certain format and labeling for this data, which you’ll look at with detailed examples.


There are a variety of reports in the Conversions ➤ E-commerce section of reports in Google Analytics that reflect the data you send.


For products, the interactions are as follows:

  • Product impression (impressions): The user saw a listing of products, as in a category page, for example.
  •  Product click (click): The user clicked a product listing.
  •  Product detail view (detail): The user viewed a product detail page.
  • Add and remove products from the cart (add and remove): The user added or removed a product from the shopping cart.
  • Checkout (checkout): The user proceeded through the steps of the checkout process (you’ll be able to configure the number and sequence of steps).
  •  Purchase (purchase): The user successfully purchased a product or products.
  •  Refund (refund): A full or partial refund was issued.
  • For promotions, the interactions are as follows:
  • Promotion impression (promo view): The user saw a promotion, such as a sale banner.
  •  Promotion click (promo click): The user clicked a promotion.


Note that the types of interactions you’re talking about fall into two categories: those that occur when the page loadsand those that occur only when the user clicks on some element of the page.


In the first category are impressions, detail, and promo view, which all indicate something being viewed on a page. For these measurements, you can include E-commerce data in the data layer declaration when the page is loaded. 


In the latter category are click and promo click, which both indicate a click. For these interactions, you’ll need to push information to the data layer when the click occurs.


Other interactions, such as add, remove, checkout, and the purchase could fit either category, depending on the site. Some sites might take the user to the cart page when adding a product, while others might merely add the product without refreshing the page.

For checkouts, each step (billing, shipping, etc.) may be a separate page, or they may all be within a single page (using AJAX). You can deal with either scenario.


Finally, a refund is a type of interaction that may often take place outside a regular user interaction on the site (they may occur in conjunction with a customer service request, for example). You’ll examine how to handle refunds separately.



The types of interactions that can be tracked in enhanced E-commerce and the amount of data needed to support them can be overwhelming when you are considering implementation.


However, recognize that it’s not necessary to implement everything at once. There are no dependencies among the interaction types, so you can choose to implement some of them but not others (although of course, the Google Analytics reporting will show only those you have implemented).


Because of this, it’s common to start with only the most vital interactions, like the shopping cart, checkout, and completed purchases. More information about impressions and clicks can then be layered in, and finally, you can address promotions and refunds, if desired.


Product Impressions

The impressions action is used to record impressions of products as users see them throughout the site. Typically, E-commerce sites show lists of products in many places: on the home page, on category pages, on search results pages, and in related product recommendations. 


By sending data about which products are viewed in these lists (and then later, which products are clicked and purchased), you can better understand click-through and purchase behavior on a per-product and per-list basis.


Here’s an example of impressions data in a data layer:

<script>dataLayer=[{E-commerce:{impressions:[{name:"blogs",id:"MH007",price:"24.99",brand:"ThesisScientist",category:"blogs",variant:"Purple",list:"Featured Products",position:1},
{name:"Thesis",id:"MH342",price:"17.99",brand:"ThesisScientist",category:"blogs",variant:"Grey",list:"Featured Products",position:2}]}}];</script>


Note that impressions are the name of an array containing the impressions data. The array is a list of products for which you wish to record an impression on this page (only two in this example, but as many as necessary on your site). These can include all the core attributes described previously, and also two additional attributes:


the list is a name for the list of products. You can use whatever names you want; choose names that are easily understood by users of your reports to represent the product lists on your site, such as “Category Page”, “Recommended Products”, “People Who Purchased This Also Liked”, and so forth. 


The position is numeric and represents the position of the product within the list (starting with 1). You can include as many products in as many lists as are on the page.


Note  There is an 8-kilobyte limit to the amount of data sent in any Google Analytics request (approximately 8,000 characters). In typical usage, this is not a barrier, but if you have any impressions on a page, you may run afoul of this limit.


Keep track of how long your list of product data grows, and if necessary, you may need to split it into multiple requests (using dataLayer.push() to send additional events to Google Analytics with more product impressions).


Product Detail View

The detail action represents viewing a product detail page. Here’s an example of a product detail view in a data layer:



For this data, detail is the name of the object, which contains a products array with the core product attributes. (Typically for a product detail view, there is only a single product.) The detail action has an optional property, list, that can be provided in the action field object, like so:

<script>dataLayer=[{"E-commerce":{detail:{actionField:{list:"Featured Products"},products:[{name:"blogs",id:"MH007",price:"24.99",brand:"ThesisScientist",category:"blogs",variant:"Purple"}]}}}];</script>


This allows you to capture which list a user came from to arrive at the product detail page. (If you’re already tracking product impressions and product clicks, this is unnecessary, but may be useful if you’re not capturing those details.)


Note that there may be more than one type of E-commerce data included in the data layer. For example, on a product detail page, there may also be a list of products with impressions (such as “Related Products” or “People Who Bought This Also Bought...”). You can combine these in the data layer:



Cart Additions and Removals

The add and remove actions can be used to track products added to or removed from the shopping cart.



The action object can be named to add or remove as appropriate and contains one or more products. The product objects include the core attributes as well as the quantity attribute, which is numeric and indicates the number of items added or removed.



Finally, when a purchase is successfully completed, you can use the purchase action.

<script>dataLayer=[{E-commerce:{purchase:{actionField:{id:"AW699168",affiliation:"Online Store",revenue:"55.97",tax:"3.92",shipping:"",coupon:"FREE_SHIPPING"},products:[{name:"blogs",id:"MH007",price:"19.99",brand:"ThesisScientist",category:"blogs",variant:"Purple",quantity:1,coupon:"TOPHAT_SALE"},{name:"Thesis",id:"MH342",price:"17.99",brand:"ThesisScientist",category:"blogs",variant:"Grey",quantity:2}]}}}];</script>


For the purchase action, the action field object contains a number of attributes that summarize the transaction:

  • The ID is required and serves as a unique identifier for this particular purchase.
  • affiliation is optional and could denote a particular store (if you have multiple stores) or affiliate code.
  •  revenue represents the total revenue for the transaction. (This total can be inclusive or exclusive of shipping and tax, depending on how you want to see revenue in your reports.) If you don’t specify revenue, Google Analytics uses the total price for the products in the transaction.
  •  tax and shipping are optional and represent tax and shipping charges for the transaction.
  •  coupon is optional and represents a coupon applied to the overall transaction.


Then the products are included in an array for each of the products that are part of the transaction, including the core product attributes as well as the following:

  • quantity, as previously seen in add, remove, and checkout actions for the number of items of that particular product purchased.
  • coupon is optional and represents a coupon applied to a particular product.


Note  The same fields used for Google Analytics can also be used for purchase tracking for Doubleclick transaction tags (with some additional optional fields that can be used for Doubleclick).



You can also record refunds using the refund action. An entire transaction can be refunded, as in the following example:

<script>dataLayer=[{E-commerce:{refund:{actionField:{id:"AW699168"}}}}];</script> The id attribute should match the id of the original transaction.

You can also record a partial refund of only certain products in the transaction:


Here, the id in the action field object should match the id of the original transaction, and the id and quantity of each item in the products array should represent which items are being refunded.


Providing refund data in the data layer, as in this example, is a workable approach if users can obtain a refund by completing a process on your website.


However, in many cases, refunds might be issued through a customer service process that takes place outside the user interactions on the website (through online or phone support, for example).


In a case like this, you can process such interactions using GA’s Measurement Protocol to record data from a non-web application or by importing the data to Google Analytics in a spreadsheet.


E-commerce Data on User Interactions

In all of the previous examples in this blog, you included enhanced E-commerce data in the data layer declaration when the page loads. However, for some types of interactions, you may need to send it at a later time.


You can do this using dataLayer.push() to add information to the data layer upon user interaction and send that to Google Analytics using an event.


First, you’ll look at the two E-commerce actions that are always user interactions: product clicks and promotion clicks. Then you’ll take a look at cart and checkout interactions, which for AJAX sites might need to be handled using these techniques as well.


Product and Promotion Clicks

Earlier in the blog, you captured data about the impressions of products and promotions (using the impressions and promo view actions).

Now you can look at which of those impressions resulted in clicks using the click and promo click actions. You’ll need to trigger these when the appropriate user interaction occurs. You’ll recall that several approaches to tracking user interactions have been discussed:


  •  Embedding dataLayer.push() code directly in the site to listen for events on an element
  • Using Google Tag Manager’s auto-event tracking capabilities to attach events to an element

Either of these approaches is also viable for the product and promotion clicks, so you’ll look at each of them in the following sections.


Explicit Data Layer Events in Site Code

The E-commerce object for a product click looks like this:

 style="margin: 0px; width: 964px; height: 106px;">'ecommerce': {
'click': {
'products': [{ 'name': 'blogs', 'id': 'MH007', 'price': '24.99', 'brand': 'ThesisScientist', 'category': 'blogs', 'variant': 'Purple'


The action is slick, and it contains a products array with the core product attributes. (Unless there’s something very strange about your site, a user can only click one product at a time, so typically there’s just a single product in the array.)

For a promotion click, the E-commerce object looks like this:

 style="margin:0;width:954px;height:107px">'ecommerce': {
'promoClick': {
'promotions': [{
'name': 'April Foolery Clearance', 'id': 'PROMO_0401',
'creative': 'Tweedle Dee v.1', 'position': 'Store Home Banner' }]
} }


The action is promo click, and it contains a promotions array with the promotions attributes.

For each of the product or promotion links on the site, you’d like to capture the click interaction. To do that, you could call the dataLayer.push() function when the link is clicked:

<a onclick="dataLayer.push({'E-commerce': { // as above }, 'event': 'E-commerceProductClick' })">...</a>


Note  Although this example uses an inline onclick attribute to call the dataLayer.push() function, the code could be used in an event listener or any other existing JavaScript code on the site.



Google Analytics has a three-level structure: accounts, properties, and views. Access to Google Analytics is through Google Accounts, which are logins based on a Gmail address or any other email address. Each login may have different levels of permission at any level in the Google Analytics account structure.


Google Analytics collects data through tracking hits, packages of data about an interaction that are sent from your website using JavaScript, or from another source of data such as a mobile app.


Hits are grouped together in sessions, and users are tracked over multiple sessions. There are privacy provisions for notifying your users about your data collection practices and restricting the data you can collect.


Google Analytics data is based on dimensions (labels that describe data) and metrics (numeric measurements). All reports, including standard reports, custom reports, and APIs are based on GA’s dimensions and metrics.


Standard reports are pre-aggregated, meaning the numbers are precalculated. Non-pre-aggregated reports, such as a custom report or a standard report with an added segment, can be sampled, meaning that the numbers are calculated on the fly from a subset of the data if the dataset is large.


Getting a Google Login

Whether starting from scratch or accessing an existing implementation of Google Analytics, you will need a way to log in. For Google Analytics (and all other Google-y tools, such as Tag Manager, AdWords, Search Console, Google+, and so on), this requires that you have a Google Account.


If you sign up for an email address through Gmail, that’s automatically a Google Account. But you can sign up any email address (alice@thesisscientist.com, for example) as a Google Account.


Look no further than the “Sign in” option at the top right of pretty much anything Google, which will allow you to sign in with an existing account or create a new one.


It will ask you a few security questions and allow you to choose a username for a new Gmail address or to use an existing email address.


Tip  You’re better off using company email addresses than Gmail addresses for official business using Google tools since you have more control over your own email addresses (being able to reset the password with email verification if someone leaves your organization, for example).


 You’ll want anyone who needs a login to your organization’s data and settings in Google Analytics (and later, Google Tag Manager) to create an account this way. You can have many different logins, with different levels of access to your Google Analytics data.


Tip   You might wonder: “Should we share a single login?” Whether you want a shared login (e.g., analytics@thesisscientist.com) or separate logins for different personnel (e.g.,lewis@thesisscientist.com, etc.) depends on the structure of your organization’s departments, business units, or teams, as well as your internal security policies.


Think about whether multiple people sharing a password works. (For small organizations, maybe. For larger organizations, you’re going to want more granularity, control, and accountability for individuals.)


Google Analytics Premium Properties

Google Analytics is a free tool. People often ask, “Why does Google give it away for free?” Organizations with better data about their websites and marketing are more likely to spend money on advertising, which is where Google brings in the money.


As a free tool, however, it does have some limitations on how much data you can collect and process. Google also offers Google Analytics Premium, which is a paid subscription service that includes higher limits on data collection and processing, service-level and uptime guarantees, and customer support and training.


 Google Analytics Premium also offers some more processing-intensive reports and ways of retrieving data beyond what’s available in the free tool, as well as early access to beta features.


Google Analytics Premium is activated at the property level in Google Analytics, and you’ll see a flag next to any properties in your account list that are enabled for Google Analytics Premium.


Most of the features discussed in this blog are available for everyone—Premium or standard. Differences will be called out so you’ll know.


Reports and Data Structures in Google Analytics

Once the data is sent to Google Analytics, it will appear in all of the standard reports you can access in the Reports tab (or in Custom Reports in the Customization tab, if you’ve created any of those). Let’s take a look at how this data is organized into those reports and how the numbers are calculated.


Dimensions and Metrics

Dimensions and metrics are the building blocks of every report in Google Analytics, and understanding the dimensions and metrics available and how they fit together will give you a deep understanding of how Google Analytics really works, and what you can do with the data.


Dimensions are labels that describe data. They typically appear as the rows of reports. Examples include:

  • URLs: Hostname, Page, Landing Page, Exit Page, Previous Page, Next Page
  • Traffic sources: Source, Medium, Campaign, Keyword, Referral Path, Social Network
  • Geography: Country, Region, City, Metro


Metrics are measurements. They are always numerical and typically appear as the columns of reports.

  • Examples include:
  • User metrics: Users, % New Sessions
  • Session behavior metrics: Bounce Rate, Pages/Session, Avg. Session Duration, Conversion Rate
  • Campaign metrics: Impressions, Clicks, CTR, CPC


Each report in GA—whether a standard report, a custom report or even data extracted through the Google Analytics APIs—is a combination of dimensions and metrics that are extracted and calculated from the tracking hits received. Most standard reports have some sensible defaults, but allow you choices to show the data in different ways by changing the dimensions or metrics displayed.


Custom reports allow you to select completely customized combinations of dimensions and metrics. Reports also allow filtering and segmentation of data based on dimensions and metrics. For example, you can say “Show me all the Pages with Bounce Rate greater than 50%” or “Show me the Campaigns only for users located in Florida”.


You’ll get a sense for the dimensions and metrics available simply by browsing through the standard reports in Google Analytics. A comprehensive reference to dimensions and metrics is available in the Google Analytics developer documentation, which includes the labels used in the reporting interface as well as the programmatic identifiers used in the APIs.


The dimensions and metrics reference also indicates which combinations are allowed—certain dimensions or metrics cannot be viewed in the same report, either because they are logically incompatible or because the underlying data on such a combination isn’t available in Google Analytics.


Tool Overlap and Reconciliation

If you’re like most folks, you’re using multiple tools for measuring web activity, and more than likely, some of those overlap with what Google Analytics is also measuring. Your content management system, social media plugins, e-commerce system, email marketing tools, and more may all have metrics about web activity.


To the extent possible, it’s worth trying to consolidate as much as possible in a single system that is flexible enough to handle most of the data that’s most important to you, for the simple ability to see and analyze all these data side-by-side without having to stitch them together in some other way.


Google Analytics is a good candidate for bringing together as much of your online (and even offline) customer interaction as possible because of its flexibility. Much of this blog will focus on bringing these different categories of data together.


However, collecting data in Google Analytics may not be practical for you in all cases, so there are many facilities for exporting data as well.


Where you are using Google Analytics data alongside data from other sources, you should be aware that metrics will not always match exactly. This can happen for a whole variety of reasons. Metrics that seem like they should be the same are often defined in subtly different ways between tools or are measured in different ways.


Compare carefully, and don’t assume that numbers between different tools are comparable unless you understand their definitions clearly and do some cross-checking of your own.


Overall, though, you should expect metrics to agree directionally and proportionally between tools, and you shouldn’t get bogged down in the minutiae of reconciling tools when you could better spend your time making decisions based on data that is good enough.


Google Analytics Documentation

Even with this excellent blog in hand, you’ll probably need to reference the documentation for Google Analytics at some point. There are actually two major documentation collections for Google Analytics:


The Help Center, accessible from the top menu, provides information about the reporting and administration functions in Google Analytics. If there’s a report or setting you don’t quite understand, it should give you some context on what it’s for and how it works.


The Developer Center has all the documentation of the Google Analytics JavaScript tracking codes, APIs, and other technical information about Google Analytics. It makes a great supplement to this blog, and some of its reference documentation and handy tools will be referred to for further background.


Google Analytics Tracking code

This blog focuses on the latest generation Google Analytics tracking library, analytics.js, which is part of GA’s suite of upgrades and expanded features called Universal Analytics.


There are other, older Google Analytics tracking libraries, such as urchin.js and Google Analytics.js. These worked in similar ways, but the specifics of syntax are different, and not all features described in this blog are available with older libraries.


The analytics.js library has been the default code for new properties in Google Analytics since 2014, and an upgrade process is available for properties that predate the change. You will see a notification about the upgrade process in the Admin section if you haven’t updated (and you’ll be able to see the older code on your site).


Although the older code will continue to work and gather data for some period of time, if you want to take advantage of any of the newer features of Google Analytics, you will want to upgrade as soon as possible (and eventually it will become mandatory).


The Google Analytics Developer Center contains documentation for the legacy code and an upgrade center to guide you through the process.1


Arguments and Field Names

Depending on the command, Google Analytics accepts values for additional fields that affect how it works or the data gathered. As you saw earlier, for example, the create command indicates the property ID, for example.


In many cases, there are two ways you can specify these values. For some, you can specify them as arguments directly in the Google Analytics function call: ga(create', 'UA-XXXXX-YY', 'auto');


This is the format you’ve already seen, and it is a convenient way to provide some of the most common field values. Since it uses function arguments, notice that the order is important, and the function expects the arguments to occur in a particular position.


There’s an alternative syntax available as well, and it’s the only way to specify some of the lesser-used fields, which do not have a parameter equivalent. This alternative syntax uses an object for the fields and values:

  • ga('create',
  • { 'trackingId': 'UA-XXXX-Y', 'cookieDomain': 'auto' });

Since the object includes the name for each field, the order doesn’t matter. Both of these syntaxes are equivalent and work in the same way.


Getting the Code on the Page

So the instructions say “copy and paste this code into every web page you want to track,” but fortunately that’s probably easier than it sounds. In this era, chances are that you have a content management system with some manageable number of page templates (rather than individual, distinct HTML files for each page of the site).


If that’s the case, you just need to get the code into one or more templates so that it’s automatically included in each page of the site. You do want to make sure that you get all the templates because any missing pages will not be measured in Google Analytics. As far as Google Analytics is concerned, if there’s no tracking code on the page, it’s as if it doesn’t exist.


Multiple Domains As One Site

Sometimes, you need to treat multiple domains as a single site. This is most common with sites with third-party components, such as a shopping cart, donation site, or other application where some functionality is on a different domain.


For example, your site might be thesisscientist.com, but to blog a hotel stay, users end up on thesisscientist.com.example.biz instead, a third-party site.


If the regular Google Analytics tracking code were used on such a site, there would be a separate _ga cookie for thesisscientist.com and thesisscientist.com.example.biz.


Since each site would have a different set of client IDs, Google Analytics won’t connect behavior on one site with the other—for example, did someone who viewed a particular page on your site end up booking a hotel room on the third-party site?


That’s a question you would probably want to be able to answer, but to do so, you will have to coordinate the client IDs between the two sites.


This is known as cross-domain tracking in Google Analytics. Google Analytics provides some functions to append a special parameter to the links or forms that take a user from one site to another that contains the client ID so that the receiving site uses the same client ID.


The links look like this: http://thesisscientist.com.example.biz/hotelbooking.php?_ga=1.1821195.1441315.1362115890410


The linker parameter _ga contains the client ID for the receiving site. Let’s take a look at how to set this up.


Decorating Links

Next, you have to append the linker parameter to links on either site that go to the other. This is known as “decorating” the links—like hanging a little ornament on the end. Google Analytics provides several utility functions to do this in a plugin called linker.


The simplest option is to use the autoLink command, which allows you to specify a list or pattern of domains to be included and automatically decorates links that appear on your web pages.

ga('require', 'linker');

ga('linker:autoLink', ['thesisscientist.com', 'example.biz']);


The first line loads the linker plugin. The second calls the autolink command and supplies an array of domains for which you want links to be decorated. The domain list uses a substring match against the destination of the link—notice you can list example.biz or thesisscientist.com.example.biz, depending on how specific you want to be.


Tip   Instead of a list of strings, you can also use a regular expression to match domains:

ga('linker:autoLink', [/^thesisscientist.com(resorts\.com|\.example\.biz)$/]);


The autoLink command works well for automatically decorating links on most websites. Some pages may include scripts that prevent auto-linking from functioning, so as with any JavaScript, you should test thoroughly before deploying on your site.


If auto-linking doesn’t work for your site, the linker plugin also provides a function linker: decorate for manually decorating your links. This function is useful in a number of situations aside from standard links:


  • Decorating an HTML form that posts from one site to another.
  • Decorating the destination of an iFrame of one site’s content within the other.
  • Decorating links if the autoLink function doesn’t play nicely with existing scripts on your site.
  • Specific examples of these cases are available in the Google Analytics Developer Center.


Page Content Variables

Constant String: This variable type can be used for a simple string. Even though it’s not dynamic, this variable can be useful for a string that’s used in multiple tags or triggers, because it allows a single place to update the value.


Lookup Table: The lookup table variable type allows a series of comparisons to pick a value from a list.


Random Number: This variable contains a random number between 0 and 2,147,483,647. This is available as a built-in variable. Providing Data to Google Tag Manager with a Data Layer.


In some cases, you’ll be able to capture information of interest directly from the page using variables for URLs, DOM Elements, and so on. But at times, there is information you might like to capture that is not part of the page—metadata about the page itself or the user viewing it that is not explicitly displayed in the page’s content.


Examples could include information such as a page’s category (where that isn’t made explicit in the URL) or a user’s identity (for a site where users log in).


Google Tag Manager uses an object for communication of this type of information, called a data layer. The data layer provides a centralized list of information made easily accessible to Google Tag Manager, but which remains invisible to the user viewing the page.