Google Analytics Tag Manager (90+ New Google Analytics Hacks 2019)

How to use Google Analytics Tag Manager 2018

How to use Google Analytics Tag Manager 2018

Now that you’ve looked at the basic building blocks of Google Tag Manager, let’s work through creating your first functioning tag: the standard Google Analytics pageview tracking tag. Let’s assume you’ve already created a Google Tag Manager container and added the container code to your site.

  • First, create a Google Tag Manager tag for Google Analytics.
  • In the container’s Tags section, select the New button.
  • Edit the tag name at the top (“Untitled Tag”) to give the tag a name: “GA - Pageview”

 

Note  You’ll want to devise a sensible naming convention for your tags, triggers, and variables, especially if more than one person adds and edits them in Google Tag Manager.

 

Typically, tags are named by starting with the type or tool (in this case, “GA”), what’s being measured (“Pageview”), and then any additional information needed to describe the tag.

 

  • Select the tag from the list of supported tag templates: Google Analytics. 
  • Select the Continue button.
  • Choose Universal Analytics as the tag type
  • Select the Continue button to fill in the Google Analytics tag’s options.
  • Enter your property ID in the Tracking ID field
  • This is the UA-XXXXX-YY identifier for your web property in Google Analytics. 
  • Google Tag Manager uses this field to fill in the value in the Google Analytics code’s create command.

 

Select Track Type ➤ Page View as the type of Google Analytics tracking you’d like to use. This corresponds to the send command with the hit type pageview, as seen in the Google Analytics tracking code.

 

These are all of the settings you need to supply if you are using the standard, out-of-the-box Google Analytics tracking code since they correspond to the two commands in Google Analytics (create and send). However, you’ll notice that there are many more settings available under More Settings. 

 

These correspond to additional settings passed in the Google Analytics tracking code, such as a tracker name (Advanced Configuration ➤ Set Tracker Name) and cross-domain tracking features (Cross Domain Tracking). 

blog

There are fields that affect additional types of data, such as content groups, e-commerce data, and custom dimensions and metrics, which are features explored in further blogs.

 

Although many additional fields in Google Analytics are available as settings in these categories, you can also use the Fields to Set section, which is equivalent to using the field object in your Google Analytics code.

 

If there are any settings that you need to change in Google Analytics that do not have a corresponding setting in Google Tag Manager, you can use Fields to Set.

 

Two important notes about the default Google Analytics tag settings in Google Tag Manager:

If no tracker name is specified, Google Tag Manager assigns a random tracker name to each Google Analytics tag. In this way, every tag in Google Tag Manager creates a differently named tracker.

 

If no cookie domain is specified, Google Tag Manager uses the default option (the full domain name, minus www.), not the auto option. If we’d like to use the auto option, we need to use the Fields to Set to set cookieDomain to auto.

 

 Before you save your new Google Analytics tag, you need to assign at least one trigger so that it executes. Still, in the tag creation screen, select the Continue button to assign triggers to your tag.

 

You have the opportunity to select from some basic trigger types. Since you want your default Google Analytics pageview tag to execute on every page, you can select the All Pages trigger provided.

 

At this point, you are ready to save your tag. Select the Create Tag button at the bottom of the page to save and return to the container overview.

 

So far, you’ve set up your Google Analytics pageview tag to execute on every page, and that’s all you really need it to do. However, it pays to do a little planning and use variables for any piece of information you might reuse. Is there anything you’ve configured so far that might benefit from using a variable?

 

You’ll remember that you just typed the Google Analytics property ID into the corresponding setting in the Google Analytics tag. If you’ve got just one tag, that’s not a big deal, but as you add additional types of tracking as you go forward, you’re going to use that property ID again.

 

If you create a variable, you can use it over and over without worrying about typos, and it will be easy to update everywhere if you need to change it.

 

Let’s create a variable for the Google Analytics property ID.

  • In the container’s Variables section, select the New button.
  • Give the variable a name: “GA Property ID”.
  • Select the type of variable: Constant String.
  • Enter your property ID (UA-XXXXXX-YY) as the value of the variable.
  • Select Save to save and return to the container overview.

 

Now that you have a variable for the property ID, let’s update the Google Analytics tag to use it.

  • In the container overview, select your Google Analytics tag to edit.
  • In the Tracking ID field, delete the existing value that you typed in directly earlier.
  • Select the building block icon on the right of the Tracking ID field to see a list of macros to fill in.
  • Choose the {{GA Property ID}} variable that you created (see the screenshot below).
  • Select Save to save and return to the container overview.

 

When you include a variable in a field in Google Tag Manager, you can either select it from the block drop-down or type it indirectly. Either way, at the time the tag executes {{Variable Name}} will be filled in by Google Tag Manager with the value of the variable.

 

What Comes Next

So far, you’ve set up a tag with a trigger and a variable. However, note that so far nothing has changed on the website. None of the changes in Google Tag Manager are made life until you publish them to the site. will talk about the publishing process and testing tools that you can use to ensure that everything is in order before you make the code live.

 

What you’ve set up so far covers the basic Google Analytics pageview trackingIn further blogs, you’ll look at all the other types of data you might send to Google Analytics, and how to accomplish that with Google Tag Manager.

 

 MIGRATING TO Google Tag Manager

code

If you’re just starting out with Google Analytics, you have the opportunity to create all of your tags in Google Tag Manager from the start. But what about sites that already have an existing implementation of Google Analytics (with code directly on the pages), where you’d like to migrate to using Google Tag Manager to manage the tags?

 

You want to go through this migration without disrupting your data collection in Google Analytics. Here’s the recommended process:

 

Create a Google Tag Manager container and add the container script to your website. Do not change or remove any of the existing Google Analytics code at this point.

 

Create a new property in Google Analytics. This will be a temporary property for testing, which you can delete after the migration is complete.

 

Implement Google Analytics tags in Google Tag Manager using the new property ID. The goal is to re-create any existing Google Analytics tracking on the site, using tags in Google Tag Manager. This includes the standard pageview tracking, as well as any additional tracking, such as events, e-commerce, custom dimensions, and so forth.

 

Since you have both your existing property and the new property tracking from Google Tag Manager, you’ll be able to compare to ensure that you’re tracking all the same things and that the numbers match.

 

Continue to refine until you are confident that you have replicated your existing implementation with Google Tag Manager.

 

Last, the tricky part. At approximately the same time, you want to do two things:

  • Remove all existing Google Analytics code from the website. This includes both the standard page view tracking code as well as any additional custom code you’ve added.

 

  • Switch the property ID in the Google Analytics tags in Google Tag Manager from the new property to the old. (This is quick—especially if you use a variable for the property ID as recommended earlier).

 

Removing the old code can be the tricky part here. Ideally, you can do it all in a single push, but it depends on your site’s deployment process and your content management system.

 

Remember that any gap between removing the old code and switching the property ID in Google Tag Manager means a gap of time in which you weren’t capturing data to your property in Google Analytics. (Conversely, any overlap would result in double counting.) So you want to time this transition carefully and do it during a noncritical time.

 

Testing Your Implementation

testing

That Publish button is really enticing in Google Tag Manager (GTM), but you should know what you’re about to do before you click it. This blog explores the testing and publishing process in Google Tag Manager, as well as testing and evaluating data accuracy in Google Analytics to ensure that you’ve set up your tags correctly.

 

Publishing in Google Tag Manager

You can set up a collection of tags, triggers, and variables in your container. Until you deploy them using Tag Manager’s publishing process, Google Tag Manager won’t include them in the container when it’s loaded on a web page. You have to explicitly choose to publish your changes before they take effect.

 

The container overview always includes information about the current draft, the published version, and how many tags, triggers, and variables have changed between them. When you’re ready to try out the changes you’ve made, you should first preview them on the site before publishing.

 

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.

 

This is the most important thing to understand about Preview mode: it works on your live website, but only for you.

 

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 AND DEVELOPMENT, TEST, AND STAGING SITES

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.

 

Publish Your Container

Publish Your Container

If you’re satisfied with what you see in Preview mode, you are ready to publish your changes and make them live for all the viewers of your website.

 

To publish, click the Publish button. Google Tag Manager will indicate the changes that are being updated in the currently published version and then ask for a confirmation. Once you confirm, Google Tag Manager publishes the changes to the website.

 

Version Management

Each time you publish your container, Google Tag Manager creates a new version. Versions are sequentially numbered, fixed snapshots of the container’s tags, triggers, and variables.

 

While the container overview always shows the current draft contents, it also provides the ability to view the currently published version (right) or to view a list of all previous versions (center). You can also view the list of all versions in the Versions tab in the top navigation.

 

The list of previous versions includes information about when the version was created and published, and who published it. By selecting a version, you can see a more detailed audit trail of edits and publication history for the version, as well as the tags, triggers, and variables it contains.

 

You can give the version a name and record notes about it in the Actions drop-down (at the right of the listing in the list, or at the top right in the version details). Naming the version adds a descriptive label in addition to the version number (such as “Added Google Analytics tag”). Adding notes allows more extensive descriptions of changes or details.

 

For any version, you have the opportunity to Preview, Publish, or Edit as a New Version. This allows you to revert to an earlier working version of your container if you have inadvertently published something that isn’t working correctly.

 

You can also Share Preview, which gives you the ability to send a link to someone else to view the Preview version in their browser. (Remember that Preview mode uses a cookie and only appears in your browser. The shareable link allows someone else to see the same thing.)

 

Finally, you may delete a version if desired. Deleted versions are permanently removed, so you should only do this if you need to remove versions that are broken or that you want to prevent from being republished to the website.

 

GTM’s version management tools create a very good record of what’s been done in Google Tag Manager and when changes were published to your site, as well as provide the ability to revert changes quickly if anything goes wrong. 

 

You also have the opportunity to create a version from the current draft without publishing it, using the drop-down on the Publish button on the container overview. This allows you to create a saved checkpoint of progress you have made without publishing it yet.

 

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.

 

Chrome Tag Assistant

The best at-a-glance tool for inspecting which Google Analytics tags are included on a page and what they are doing is the Tag Assistant, an extension provided by Google for the Chrome web browser.

 

It installs an icon onto the Chrome toolbar that contains information about Google-related tracking tags that are included in the page currently being viewed in the browser, such as Google Tag Manager, Google Analytics, AdWords, and DoubleClick tags.

 

Clicking the Tag Assistant icon reveals information about the tags, such as the container ID for Google Tag Manager or the property ID for Google Analytics, as well as suggestions or warnings for the tags if they seem to be implemented in a non-standard way or don’t seem to be functioning correctly.

 

The Tag Assistant is an easy way to check whether Google tags are included in a page, and which Google Tag Manager container or Google Analytics properties are being used to track the page.

 

Google Analytics Debug Mode

Google Analytics Debug Mode

To see more information about the data gathered and sent by Google Analytics, Google Analytics has a debug mode of its own. Enabling the Google Analytics to debug mode prints information on what Google Analytics has done to the JavaScript console, which is a log in your browser that tracks JavaScript warnings, errors, and messages.

 

Enabling Google Analytics Debug Mode

There are two ways that you can enable GA’s debug mode: by altering the Google Analytics tracking code (through the Google Tag Manager tag), or by using a browser extension in Chrome.

 

Altering the Google Analytics tag in Google Tag Manager requires publishing a new version of your container to take effect while using the extension you can turn the debug mode on and off at will (in your browser only).

 

Alter the Google Analytics tag in Google Tag Manager. In your Google Analytics tag in Google Tag Manager, in the More Settings ➤ Advanced Configuration section, there is a setting labeled Use Debug Version. Setting this option to True enables GA’s debug mode.

 

Although you could always set this option to True, keep in mind that this will enable GA’s debug mode for all visitors to the site (although visitors won’t see anything different unless they look at their browser’s JavaScript console).

 

A better solution is to use the {{Debug Mode}} variable in Google Tag Manager, which is True only when Google Tag Manager is in the Preview mode discussed earlier in the blog.

(You’ll have to enable this variable before using it in your Google Analytics tag.) Of course, you need to publish the container for the altered tag to take effect.

 

Use the Google Analytics Debugger Chrome Extension. If you are using Chrome as your browser, you can install the Google Analytics Debugger Extension, which allows you to turn on Google Analytics debug mode on any website that you are viewing.

 

Like the Tag Assistant extension described earlier, this extension installs an icon in the Chrome toolbar that allows you to turn Google Analytics debug mode on and off. Simply click the icon to turn it on (which will reload the current page in your browser window).

 

Click again to turn it off. Using the extension allows troubleshooting at any time, without entering GTM’s Preview mode or publishing changes to your container.

 

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. (You can also find it in the View menu under Developer, or Ctrl+Shift+J on a PC or Cmd+Opt+J on a Mac.) 

 

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

Browser-based tools check whether appropriate tracking code is included in a page and what data it sends. You can also take a look at the tracking data received by Google Analytics.

 

The majority of reports in Google Analytics take some time to calculate, and so aren’t up-to-the-minute, but the Real-Time reports show a live stream of data just as it’s received by Google Analytics. You can go to your site, view a page or trigger an event, and see the data appear in the Real-Time reports.

 

These reports cover a variety of data, but the two reports most useful for troubleshooting are the Content report (which shows pageviews received by GA) and the Events report (which shows events received by GA). 

 

Google Tag Manager is a free tag management system that provides capabilities to manage, version, and publish tracking tags to your website. As with Google Analytics, you can log in to Google Tag Manager using a Google login, and there are multiple levels of permissions that can be assigned to users.

 

Google Tag Manager container is managed through a web interface and is a collection of tags (JavaScript or image code snippets to be included), triggers (rules to specify when to fire or block tags), and variables (pieces of information pulled from the page to fill in tag data or trigger criteria).

 

The Google Tag Manager container script goes on every page on the website(s) being managed with Google Tag Manager, replacing the need for adding tags directly to those pages.

 

Google Tag Manager and Google Analytics APIs

An application programming interface (API) is simply a standardized way for a third-party application or script to read or write data to another tool.

 

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

api

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

api_google

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.

 

GTM Container JSON Format

The GTM API uses a standardized JSON object format to represent a container version’s settings, tags, triggers, and variables.

 

This JSON object format is specified in the GTM documentation and it is used in the GTM API to represent the contents of the container or to update a container with new settings, tags, triggers, or variables.

 

We can also export and import containers from within the GTM interface using this same JSON format. These options are found the container settings of the GTM Admin area.

 

Google Analytics APIs

Google Analytics has two types of APIs: configuration and reporting.

 

Reporting: The reporting APIs access the same data available in GA’s standard and custom reports. You can choose the dimensions and metrics, date ranges, and filtering and sorting options, and apply segments to obtain data from GA, just like in the web reporting interface.

 

Configuration: Like the GTM API, GA’s configuration APIs focus on setup—the things that can be done in GA’s Admin area, such as setting user permissions, linking AdWords accounts, setting up views and filters, and creating goal conversions.

 

Reporting APIs

Reporting APIs

The main reporting API is the Core Reporting API, which accesses the majority of data in GA. It’s supplemented by the Multi-Channel Funnels Reporting API and the Real-Time Reporting API, which access alternative types of data. The Embed API and Metadata API provide additional convenience features around the Core Reporting API.

 

Core Reporting API

The Core Reporting API allows access to the same data available to standard and custom reports in the GA web reporting interface. The ability to access this data programmatically opens a world of possibilities for custom reporting and dashboarding, integrating GA data into applications or web content, joining with marketing channel or internal application data, and more.

 

 The Core Reporting API is accessed by specifying a query in a request. The API responds with a table of results for that query. Queries in the Core Reporting API have a number of options; an overview follows.

 

Specifying a View

Each query must specify the ID of a view in GA from which you’d like to pull data. (Of course, the authorized user must have access to that view.) You can find the view ID in the view settings in the Admin area of GA, or by using the Management API.

 

Dimensions & Metrics

Dimensions & Metrics

Just as reports in GA’s web interface are made up of dimensions and metrics, so are queried in the Core Reporting API. Every query must have at least one metric and can contain up to ten metrics and seven dimensions.

 

Not all dimensions and metrics are compatible in the same query. In the GA documentation, there’s a tool called the Dimensions & Metrics Explorer.

 

It allows you to see all of the names and descriptions of dimensions and metrics available, along with their names in the GA web reporting interface and their compatibility in API queries. The names of dimensions and metrics in the Core Reporting API are prefixed with ga: (e.g., ga:pagePath or ga:sessions).

Sort, Filter, and Segment

Core Reporting API query can be sorted by any of the included dimensions or metrics in ascending or descending order. (Alphabetical order is used for dimensions except for dates, which are sorted chronologically; the numerical order is used for metrics.)

 

If no sort order is specified, GA sorts by the first dimension, which is almost never what we want! Typically, you’re interested in sorting by a basic metric such as ga:sessions or ga:pageviews, in descending order.

 

Like a report in the web interface, you can filter the rows of the query result. Filters can include or exclude rows based on a dimension or metric value, including regular expression matches for text. They can be combined with logical AND and OR.

 

Additionally, like reports in the web interface, you can apply segments. You can select from the built-in segments, a segment you’ve previously created in the web interface for your user login, or specify the criteria for a segment on the fly.

 

Date Ranges, Results, and Pagination

Each query includes a time period. The API supports some common shorthand, such as today, yesterday, and 30daysAgo. Or you can specify a date range.

 

By default, the query returns 1,000 rows of results (with whatever sort order is specified). You can specify the number of rows to return from 1 and 10,000. If there are more than 10,000 rows, you can specify a starting row for a request.

So, for example, you could request the first 10,000 rows, and then make a second request for rows beginning with 10,001 (up to 20,000), and so on.

 

Query Explorer Tool

Basically, anything you can imagine doing in a custom report in the GA web interface can also be done via the Core Reporting API. A good tool for exploring the capabilities of the Core Reporting API is the Query Explorer Tool.

This tool uses a system of drop-down menus to fill in a Core Reporting API request, which you can then submit and see the results (or download in a text file).

 

Multi-Channel Funnels Reporting API

The Multi-Channel Funnels Reporting API allows access to the data available in the reports through Conversions ➤ Multi-Channel Funnels in GA. This data deals with traffic sources over multiple sessions leading up to a conversion.

 

Since this API deals with multi-session data, accessing and handling this data is slightly different from the Core Reporting API (which is based on individual sessions), but its applications are similar:

 

customized reporting and dashboarding, integration with marketing channel data, and so forth. Dimensions and metrics in the Multi-Channel Funnels Reporting API use the mcf: prefix.

 

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.

 

Metadata API

The Metadata API is a convenience API for GA that lists the dimensions and metrics available in the Core Reporting API. This is similar to the Dimensions & Metrics Explorer tool mentioned previously, but it allows programmatic access to this information.

 

Management API

The Management API is used to access and update configuration settings in GA, including the following:

  • Create, access, and update the settings of web properties.
  • Create, access, and update the settings of views.
  • Add and update user permissions.
  • Create, access, and update filters and apply them to views.
  • Create, access, and update goal conversions.
  • Add and update AdWords links.
  • Create, access, and update custom dimensions, metrics, and data sources.
  • Create, access, and update Content Experiments.
  • Create and retrieve unsampled reports (GA Premium only).

Google Analytics Unique Page Views

Google Analytics Unique Page Views

You’ll recall that the basic Google Analytics tag captures page viewsA page view is only one of several hit types that represent different kinds of data that Google Analytics can collect. Besides the pageview hit type, two additional hit types, event and social, can be used to collect other kinds of interactions.

 

Event and social hits are similar to each other. Event hits are designed for any type of interaction within a page, while social hits are specifically for social media interactions.

 

Each appears in its own set of reports (events in the Behavior reports in Google Analytics, social in the Acquisition reports). Let’s start by focusing on events, and look at social interactions later in the blog.

 

To send an event to Google Analytics, you can use the following JavaScript command:

ga('send', 'event', 'category', 'action', 'label', value, {'nonInteraction': false});

 

The category is required and represents a way to group similar types of events for your site. For example, you might have categories such as Downloads, Outbound Links, and Videos. 

 

The action is also required and describes the interaction within the category. For example, the Videos category might have actions like Play, Pause, or Finish.The label is an optional text field to further describe the event.

 

The value is an optional integer that describes the event. There are no specific units associated with the value, so it might be dollars, seconds, points in a Google Analytics me, or any number that fits to describe the event.

 

Finally, the non-interaction parameter controls whether the event affects the bounce rate. By default, this is false, meaning that if a user lands on a page and then triggers an event, that session is no longer a bounce (which is usually what’s desired if the event represents a user interaction).

 

By setting it to true, the event no longer counts as an interaction and the session is still a bounce unless another interaction occurs (which may be what’s desired for an event that automatically occurs when the page loads, such as a video that auto-plays, for example).

 

The category, action, and label appear as dimensions in Google Analytics, and the value as a metric. These dimensions and metrics appear in the Events report in the Behavior section of Google Analytics, and whatever data you send with your event code are the values that appear in your Google Analytics reports.

 

Because of this, it’s important to design naming conventions for events that make sense and are consistent. The examples in this blog have a number of suggestions for how you might name events, but you should do it in a way that is most useful and understandable for your Google Analytics users.

 

Of course, Google Tag Manager has a built-in tag to include Google Analytics’s event tracking code, just like for your pageview tracking. In the Google Tag Manager tag, you still get to specify the same parameters (category, action, and so on).

 

CREATE A BASIC Google Analytics EVENT TAG IN Google Tag Manager

EVENT TAG IN Google Tag Manager

 

You can add a Google Analytics event tag in Google Tag Manager by following these steps:

Create a new tag.

  • Select Google Analytics ➤ Universal Analytics as the tag type.
  • As you did in the pageview tag, you’ll fill in the Tracking ID with the {{GA Property ID}}
  • Select Track Type ➤ Event.
  • You’ll notice that this reveals input fields for category, action, label, value, and non-interaction
  • For now, you can fill values in by directly typing them into the event fields.
  • In most cases, you will use variables to fill them with relevant information from your page.
  • Select Continue to proceed to the next step.
  • Next, choose the tag’s triggers. You can skip the triggers for now.
  • Choosing the right triggers will be another key topic for this blog.
  • Select the Create Tag button to save the tag, giving it a name: “GA – Event”.

That’s the basic process. In the rest of the blog, you’ll learn about the variables and triggers to use to fill in the blanks, and how those relate to measuring specific actions on your site.

 

Design Patterns for Events in Google Tag Manager

Design Patterns for Events in Google Tag Manager

The tag itself for event tracking is straightforward. The trick is to create the right triggers (to say when the tag should fire) and variables (to capture the right information about what interaction occurred and to fill in the category, action, and other information). 

 

This blog looks at several general design patterns for using Google Tag Manager to track events, and then at a number of specific examples of the most common types of items to be tracked.

 

There are several approaches to tracking events in Google Tag Manager because you can choose how much of the code is handled in Google Tag Manager versus code that is included in the page itself. Whichever approach makes sense for you depends on your capabilities and your level of access to add or change the code in your site’s pages or templates.

 

All of these approaches make use of GTM’s data layer. In addition to setting information in the data layer at the time the page loads , you can send additional messages to the data layer at any time, which is how events within a page can be triggered in Google Tag Manager.

 

You can add information to the data layer about an interaction using the following code:dataLayer.push({'event': 'event-name'});

 

This code adds a new message, or a list of properties, to the data layer. The event property is used by Google Tag Manager to trigger tags. You’ll name different events that occur on your pages and use those names to trigger your tags.

 

You can include additional properties with details about the event to pass additional information to Google Tag Manager variables, which you’ll see in examples throughout this blog.

 

The data layer, then, comprises a sequential list of messages about different events that occur on the page. In fact, Google Tag Manager creates several of its own events (the names of which are all prefixed with gtm). These Google Tag Manager events are:

 

Google Tag Manager.js (labeled “Pageview” in the debug panel) is the first event in the data layer and is sent as soon as the Google Tag Manager container is loaded. This is the default event for tags with page-based triggers (such as your Google Analytics pageview tag).

 

Google Tag Manager.dom (labeled “DOM ready” in the debug panel) is sent when the DOM is ready. This means your browser has loaded the structure of the DOM, but not necessarily that all page content has been loaded or rendered.

 

Google Tag Manager. load (labeled “Page Load” in the debug panel) is sent when the page is completely rendered in the browser, including images, scripts, and other contents.

 

GTM’s debug panel will show any messages pushed to the data layer, as well as the current value of any variables after the message is pushed. You can click an event in the list on the left and select the Variables or Data Layer tabs at the top to see this information.

 

JAVASCRIPT AND DOM EVENTS

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.

<script>

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

</script>

 

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

The first design pattern uses features of Google Tag Manager to move code from the page into Google Tag Manager. In many cases, you may be able to use GTM’s auto-event tracking capabilities to track page interactions without adding any additional code to the page.

 

Google Tag Manager has built-in capabilities to listen for clicks, form submissions, errors, and more. These can be set up with a set of built-in variables and easy-to-configure triggers that don’t require adding your own JavaScript code. This approach has the advantage of reducing or eliminating your reliance on adding code to the site itself.

 

When you create a tag in Google Tag Manager, you are prompted to select a trigger. You previously used the All Pages trigger for your pageview tracking tag for Google Analytics, and Some Pages gives you the option to fire tags only on a subset of pages.

 

The Click and Form trigger options allow you to track those types of interactions (the most common), while selecting the More button gives additional options.

 

These triggers use built-in capabilities for deploying event listeners on your site using Google Tag Managerwithout you needing to write any code to enable them.

In addition to the triggers, there are also variables that correspond to information collected about the element that was clicked, the form that was submitted, and so on. These built-in variables can be enabled or disabled, and you’ll want to make sure that you enable the relevant variables before using the corresponding trigger type.

 

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>

 

CREATE A BASIC CLICK TRIGGER IN Google Tag Manager

BASIC CLICK TRIGGER IN Google Tag Manager

Let’s look at the basic process for adding a click trigger in Google Tag Manager.

  • In the Triggers section in the left-hand navigation, select the New button to create a new trigger.
  • For the event that causes the trigger, select Click.
  • Choose whether the trigger applies to clicks on all elements, or only clicks on links (see the screenshot below; more on this choice in the next section). Then select the Continue button.
  • (Optionally, if Just Links is selected) Choose to filter pages where this trigger is enabled.

 

Then select the Continue button.

Choose to listen for All Clicks (it would be uncommon to want to trigger the same event on all clicks) or Some Clicks, which allows you to specify one or more filters.

 

The filter can be based on the click variables described earlier, or any other variables you have in Google Tag Manager (see the screenshot below). You’ll see a variety of examples in this blog.

 

Save the trigger, giving it a name describing the conditions it matches, such as “Clicks – Button Links”.

 

All Elements and Just Links Target Types

When you create a Click trigger, there is a target type option with two choices: “All Elements” and “Just Links”. Choosing All Elements allows you to listen for a click any element of the page, while Just Links applies only to links (<a> elements).

 

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:

dataLayer.push({
'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.

 

IDS, CLASSES, AND DESIGNING FOR TRACKABILITY

Being able to use Google Tag Manager to find the elements you want to track within the content of your page is really important. This is most easily accomplished by providing some descriptors that will help identify the correct element(s). The class and id attributes are among the most useful.

 

The class and id attributes are an important part of the DOM. An element can have an id, which must be unique within the page (it applies to only that element). It can also have one or more classes, which represent a particular kind of element. Multiple elements can have the same class, and a single element can belong to multiple classes (separated by spaces).

 

Google Tag Manager has variables for {{Click ID}} and {{Click Class}}, and they can be an easy way to select the correct elements. Without them, or some other attributes (like link URL) to help you select the correct element, as a last resort you would have to instruct Google Tag Manager like so:

 

Find the <a> element in the third <li> in the second <ul> in the <p> with id=content. You can see how this approach is fragile and easily breakable if the content of the page changes. Ensure that your site templates are adequately structured so that you can select the elements you want without resorting to these methods.

 

Design Pattern 2: Custom JavaScript in Google Tag Manager

Auto-event tracking is great, but it works only under certain circumstances. If there are events that you’d like to track outside the situations Google Tag Manager supports, you’ll have to use some custom JavaScript to handle those. One option would be to include that JavaScript on your site (see the upcoming “Design Pattern 3” section).

 

Better yet, though, you can include custom JavaScript in tags and variables inside Google Tag Manager, so that you can manage them there, without needing to add or change code on the site.

 

Google Tag Manager allows you to include custom JavaScript code in two different ways:

A custom HTML tag can include a script tag, which can execute any JavaScript functions you desire. You can add event listeners, add or change elements, and push events to the data layer. 

 

A custom JavaScript variable can return a value, for example, if you need to grab an element or property from the DOM, test if an element is visible, and so on.

 

You’ll make use of both of these tools in the examples in this blog. These tools will allow you to create custom event listeners for interactions outside what Google Tag Manager can track using its auto-event tracking. These examples are where some knowledge of JavaScript and the DOM becomes useful (see the sidebar earlier in the blog for more information).

 

PRO TIPS FOR JAVASCRIPT NINJAS

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.

 

Design Pattern 3: Explicit Data Layer Events in Site Code

The last design pattern for event tracking in Google Tag Manager uses code to specify the category, action, and other data for the event explicitly on the page.

<a onclick="dataLayer.push({'event': 'customEvent', 'eventInfo': {'category': 'Button',

'action': 'press'}})">...</a>

 

Here an event name ('customEvent') is specified, as well as the category and action you’d like to send to Google Analytics. 

 

This is flexible for your site’s developers since you only need a single event tracking tag in Google Tag Manager to handle many different possibilities. Its disadvantage is that you need to add information about the events to your pages by adding code directly.

 

Note Although this example uses an inline on click 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.

 

This approach does work well if you already have Google Analytics event tracking code on your site and are migrating to Google Tag Manager, and wish only to make a simple change to the existing code for these legacy events. For example, you might already have code like this:

 

ga('send', 'event', 'Button', 'press');

This would be easy to simply change to the following:

dataLayer.push({'event': 'customEvent',

'eventInfo': {

'category':'Button',

'action': 'press' }

});

 

This approach doesn’t really get you the full range of benefits of Google Tag Manager (managing and testing code within GTM), since you’re including code directly in the page. There are, however, a number of advantages to this pattern.

 

It gives you a quick and easy path to update existing event code on the site to use Google Tag Manager.

 

It’s also developer-friendly, in the sense that if you have developers creating site code, they can easily add events without needing to interact with Google Tag Manager.

 

Obviously, there is a trade-off between centralizing control in Google Tag Manager and allowing flexibility for the site developers. With this code on the site, you can create a Google Tag Manager tag, trigger, and variables to send the data to Google Analytics.

 

CREATE A GENERIC EVENT TAG

Let’s assume that you have script on your site of the following form:
dataLayer.push({
'event': 'customEvent',
'eventInfo': {
'category':'someCategory',
'action': 'someAction',
'label': 'someLabel',
'value': 0,
'nonInteraction': false }
});


First, you’ll have to create variables for each of your event data inputs: category, action, label, value, and non-interaction.

  • In the Variables section in the left-hand navigation
  • select the New button to create a new user-defined variable.
  • For the variable type, choose Data Layer Variable.
  • For the Data Layer variable name, enter eventInfo. category (which corresponds to the name in the preceding code).
  • Save the variable, giving it a name such as “Custom Event Category”.
  • Repeat for eventInfo.action, eventInfo.label, eventInfo.value, and eventInfo.nonInteraction.

 

Now, you can create the tag and trigger to use these variables to send an event to Google Analytics.

  • Create a new tag. Select Google Analytics ➤ Universal Analytics as the tag type.
  • Fill in the Tracking ID with the {{GA Property ID}} variable that you previously created.
  • Select Track Type ➤ Event.

 

In each of the Category, Action, Label, Value and Non-Interaction fields, enter the corresponding variable you created earlir.

 

Then select the Continue button.

  • For the trigger, choose More, which will bring up a list of existing triggers. To create a new trigger:
  • Click the New button.
  • Select the Custom Event as the event to cause the trigger. Custom Event allows you to trigger on a dataLayer.push with any event name.
  • For the Event name to match, enter customEvent (which corresponds to the name in the preceding code).
  • Select the Create Trigger button, giving the trigger a name: “Custom Event – Click”.
  • Google Tag Manager saves the trigger and returns to creating the tag.
  • Save the tag, giving it a name: “GA – Event – Custom”.

 

Now, whenever a data layer.push occurs containing 'event': 'customEvent', this tag will be triggered to send an event to Google Analytics using the eventCategory, eventAction, and other values specified in the code.

 

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.

 

TRACK OUTBOUND LINKS

First, create the variable for Click URL Hostname. Then you can use that variable in creating your tag and trigger.

  • Select the Variables section in the left-hand navigation. Then select the New button to create a new user-defined variable.
  • For the variable type, choose Auto-Event Variable.
  • For the variable type, select Element URL.
  • For the component type, instead of Full URL (which is what the built-in variable already has),
  • select Host Name.
  • Save the variable, giving it a name: “Click URL Hostname”.
  • Now that you’ve created the variable, you can create the tag and trigger.
  • 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: Outbound Link
  • Action: {{Click URL Hostname}} (e.g., Example Domain)
  • Label: {{Click URL}} (the full URL, e.g., http://example.com/some-page.html)
  • 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)
  • 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 outbound 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 Hostname}} variable you created from the drop-down, and the criteria to match.
{{Click URL Hostname}} – does not end with – thesisscientist.com

 

Note If necessary, you could use a regular expression to match several hostnames (if you have the same Google Tag Manager container across multiple sites).

Select the Create Trigger button to save the trigger, giving it a name: “Click – Outbound Links”. Google Tag Manager saves the trigger and returns to creating the tag.

Save the tag, giving it a name: “GA – Event – Outbound Links”.

 

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.

 

TRACK DOWNLOAD LINKS

First, create the variable for Click URL File Type. Then use that variable in creating a tag and a trigger.

 

Create a new variable.

For the variable type, choose Custom JavaScript. Here’s the code to use:

function() {

var clickUrlParts = {{Click URL}}.pathname.split('.');

return clickUrlParts.length > 1 ? clickUrlParts.pop() : 'html';

}

This uses the existing {{Click URL}} variable, gets just the pathname part (stripping off the domain, query parameters, and anchor), finds a dot (if there is one), and returns the characters after the dot. If there’s no dot (thus, there’s no file name), assume the URL is for a web page and return HTML as the file type.

 

Save the variable, giving it a name: “Click URL File Type”.

Examples values for the {{Click URL File Type}} variable

URL of link Value of variable

/alice/map.pdf pdf
/alice/map.pdf?location=wonderland pdf
/alice/index.html html
/alice/ html

 

Now that you’ve created the variable, you can create the tag and trigger.

  • 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: Download

Action: {{Click URL File Type}} (e.g., pdf)

Label: {{Click URL}} (the full file URL, e.g., http://thesisscientist.com/park-map.pdf)

 

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

 

PRO TIP: SESSIONS LANDING ON 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>

In these cases, you can see that it would be straightforward to adapt the approach you’ve used for outbound links and downloads in the previous sections in this blog. You could trigger only when the {{Click URL}} variable begins with mailto: or tel:, for example.

 

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 ids 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>
<p class="tab">
<span class="tab-title">Tweedle Dum</span>
<p class="tab-content">...</p>
</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 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.

 

EVENTS FOR TIME SPENT ON PAGE

  • 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 user 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.

 

Scrolling

If you’re trying to measure how people engage with the content on your site, you often want to know more than just that they viewed a page: did they really read it? One way of getting at that would be to measure the scroll depth (that is, how far down the page the user scrolled).

 

This is the first example where GTM’s auto-event tracking can’t do what you need. Since the action you’re interested in isn’t a click or other action supported by auto-event tracking, you’ll need to use custom JavaScript to create your own listener.

 

EVENTS FOR SCROLL DEPTH

This setup will involve two tags. The first is the custom tag with an event listener for scrolling events, which will push messages to the data layer to indicate the events of interest. The second will be the Google Analytics event tag to send data about these to Google Analytics.

First, let’s create the event listener tag.

Create a new tag. Select Custom HTML as the type.

 

For the HTML, enter the following code:

<script id="gtm-scroll-tracking" type="text/javascript"> ;(function(document, window, config) {
// Browser dependencies, script fails silently
if (!document.querySelector || !document.body.getBoundingClientRect) { return false;
}
  Get our dataLayer ready, in case we're not in Google Tag Manager or we've got a special name var dataLayerName = config.dataLayerName || 'dataLayer';
var dataLayer = window[dataLayerName] || (window[dataLayerName] = []); var cache = {};
  Initialize our distances, for later config.distances = config.distances || {};
 checkDepth();
addEvent(window, 'scroll', throttle(checkDepth, 500));
 function getMarks(_docHeight, _offset) {
var marks = {};
var percents = [];
var pixels = []
if(config.distances.percentages) {
if(config.distances.percentages.each) {
percents = percents.concat(config.distances.percentages.each); } if(config.distances.percentages.every) {
var _every = every_(config.distances.percentages.every, 100); percents = percents.concat(_every); }
}
if(config.distances.pixels) {
if(config.distances.pixels.each) {
pixels = pixels.concat(config.distances.pixels.each); }
 if(config.distances.pixels.every) {
var _every = every_(config.distances.pixels.every, _docHeight); pixels = pixels.concat(_every); }
}
marks = addMarks_(marks, percents, '%', _docHeight, _offset); marks = addMarks_(marks, pixels, 'px', _docHeight, _offset); return marks;
}
function addMarks_(marks, points, symbol, _docHeight, _offset) { var i;
for(i = 0; i < points.length; i++) {
var _point = parseInt(points[i], 10);
var height = symbol !== '%' ? _point + _offset : _docHeight *
(_point / 100) + _offset;
var mark = _point + symbol;
if(height <= _docHeight + _offset) { marks[mark] = height; }
}
return marks;
}
function every_(n, total) {
var n = parseInt(n, 10);
var _num = total / n;
var arr = [];
for(i = 1; i < _num + 1; i++) { arr.push(i * n); } return arr;
}
function checkDepth() {
var _bottom = parseBorder_(config.bottom);
var _top = parseBorder_(config.top);
var height = docHeight(_bottom, _top);
var marks = getMarks(height, (_top || 0));
var _curr = currentPosition();
for(key in marks) {
if(_curr > marks[key] && !cache[key]) {
cache[key] = true;
fireAnalyticsEvent(key); }
}
}
function fireAnalyticsEvent(distance) {
dataLayer.push({
'event': 'scrollTracking',
'attributes': { 'distance': distance }
});
}
}
function parseBorder_(border) {
if(typeof border === 'Number' || parseInt(border, 10)) { return parseInt(border, 10); }
try {
// If we have an element or a query selector, poll getBoundingClientRect var el = border.nodeType && border.nodeType === 1 ? border : document.querySelector(border);
var docTop = document.body.getBoundingClientRect().top;
var _elTop = Math.floor(el.getBoundingClientRect().top - docTop); return _elTop;
} catch (e) { return void(0); }
}
Adapted from Window.scrollY function currentPosition() {
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"); var currScrollTop = supportPageOffset ?
window.pageYOffset :
isCSS1Compat ?
document.documentElement.scrollTop :
document.body.scrollTop;
return parseInt(currScrollTop, 10) + parseInt(viewportHeight(), 10);
}
function viewportHeight() {
var elem = (document.compatMode === "CSS1Compat") ? document.documentElement : document.body;
return elem.clientHeight;
}
function docHeight(_bottom, _top) {
var body = document.body;
var html = document.documentElement;
var height = Math.max(body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight);
if(_top) { height = height - _top; }
if(_bottom) { height = _bottom - _top; }
return height - 5;
} /*
Throttle function borrowed from:
Underscore.js 1.5.2 Underscore.js
(c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
Underscore may be freely distributed under the MIT license.
*/
function throttle(func, wait) {
var context, args, result;
var timeout = null;
var previous = 0;
var later = function() {
previous = new Date;
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date;
if (!previous) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining); }
return result;
};
}
  Cross-browser compliant event listener function addEvent(el, evt, fn) {
if (el.addEventListener) { return el.addEventListener(evt, fn); }
if (el.attachEvent) {
return el.attachEvent('on' + evt, function(evt) {
 Call the event to ensure uniform 'this' handling, pass it event fn.call(el, evt);
});
}
 if (typeof el['on' + evt] === 'undefined' || el['on' + evt] === null) { return el['on' + evt] = function(evt) {
Call the event to ensure uniform 'this' handling, pass it event fn.call(el, evt);\
}
}
}
})(document, window, {
// False if you just use the default dataLayer variable, otherwise enter it here
'dataLayerName': false,
'distances': {
Configure percentages of page you'd like to see if users scroll past 'percentages': {
'each': [10,90],
'every': 25
},
Configure for pixel measurements of page you'd like to see if users scroll past
'pixels': {
'each': [],
'every': null
}
},
Accepts a number, DOM element, or query selector to determine the top of the scrolling area
'top': null,
Accepts a number, DOM element, or query selector to determine the bottom of the scrolling area
'bottom': null,
});
</script>

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

 

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: Scrolling
  • Action: {{Scroll Progress}}
  • Select the Continue button to specify a trigger for the tag.
  • Choose More, and then select the New button to create a new trigger.
  • Select Custom Event as the event to cause the trigger. Custom Event allows you to trigger on a dataLayer.push with any event name.
  • For the Event name to match, enter scrollTracking (which corresponds to the name in the preceding code).
  • Select the Create Trigger button, giving the trigger a name: “Scroll Tracking Event”.
  • Save the tag, giving it a name: “GA – Event – Scroll Tracking”.

 

Hover and Other Interactions

google

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 in to 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:

 

dataLayer.push({
'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 addEvent 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

social

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, a 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 (which allows you to include a Tweet button on your page in the first place) 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.

 

Facebook Likes

The basic methodology for tracking Facebook likes will be similar to other examples in this blog where you’ve created custom listeners:

 

Create a Custom HTML tag with an event listener for your social action completion, to be triggered on every page (or at least, all pages where social interaction could occur). This tag will create a data layer message with the appropriate information about the social action.

  • Set up any variables you need to extract information from the data layer message.
  • Set up a Google Analytics tag with track type social, and fill in the network, action, and target using variables.

 

Since the pattern remains the same, let’s dispense with step-by-step instructions here and just take a look at the part that is different: the Custom HTML tag listener. (See the scroll tracking section for a detailed, step-by-step example of the whole process.)

 

A Custom HTML tag to listen for Facebook likes might look something like this:

 style="margin:0;width:987px;height:79px"><script type="text/javascript">/*<![CDATA[*/(function(d){var e=0;function b(f){if(typeof d.FB!=="undefined"){c()}else{if(f<30){f++;setTimeout(function(){b(f)},500)}}}b(0);function a(h,i,g,f){var j=typeof g==="undefined"?"":g;dataLayer.push({event:"socialShare",attributes:{network:h,action:i,link:j}})}function c(){FB.Event.subscribe("edge.create",function(j,h){var i=j.toLowerCase();var g="share";var f=j;a("facebook",g,f,h)})}})(window);/*]]>*/</script>

 

Note  This code assumes you’ve already loaded the Facebook API in your page and checks for existence of the FB object before adding its listener.

 

This listener uses the Facebook API method FB.Event.subscribe to call a function when a share occurs. A data layer message is pushed with the details.

 

You can now trigger a tag in Google Tag Manager using a Custom Event of socialShare and create variables for the data layer properties attributes.network, attributes.action, and attributes.link to fill in the Google Analytics social tag.

 

This listener only captures events for likes, but can easily be adapted to capture unlikes as well.

 

Video

Video

 

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.

 

The listener tag looks like this:

<script type="text/javascript">
;(function( document, window, config ) {
'use strict';
window.onYouTubeIframeAPIReady = (function() { var cached = window.onYouTubeIframeAPIReady; return function() {
if( cached ) { cached.apply(this, arguments); }
This script won't work on IE 6 or 7, so we bail at this point if we detect that UA if( !navigator.userAgent.match( /MSIE [67]\./gi ) ) { init(); }
};
})();
var _config = config || {};
var forceSyntax = _config.forceSyntax || 0;
var dataLayerName = _config.dataLayerName || 'dataLayer'; // Default configuration for events
var eventsFired = { 'Play': true, 'Pause' : true, 'Watch to End': true }; 
Overwrites defaults with customizations, if any var key;
for( key in _config.events ) {
if( _config.events.hasOwnProperty( key ) ) { eventsFired[ key ] = _config.events[ key ]; }
}
Invoked by the YouTube API when it's ready function init() {
var iframes = document.getElementsByTagName( 'iframe' ); var embeds = document.getElementsByTagName( 'embed' ); digestPotentialVideos( iframes ); digestPotentialVideos( embeds );
}
var tag = document.createElement( 'script' );
tag.class='lazy' data-src = '//www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName( 'script' )[0]; firstScriptTag.parentNode.insertBefore( tag, firstScriptTag );
 Take our videos and turn them into trackable videos with events function digestPotentialVideos( potentialVideos ) {
var i;
for( i = 0; i < potentialVideos.length; i++ ) {
var isYouTubeVideo = checkIfYouTubeVideo( potentialVideos[ i ] ); if( isYouTubeVideo ) {
var normalizedYouTubeIframe = normalizeYouTubeIframe( potentialVideos[ i ] ); addYouTubeEvents( normalizedYouTubeIframe ); }
}
}
 Determine if the element is a YouTube video or not function checkIfYouTubeVideo( potentialYouTubeVideo ) {
var potentialYouTubeVideoSrc = potentialYouTubeVideo.class='lazy' data-src || '';
if( potentialYouTubeVideoSrc.indexOf( 'youtube.com/embed/' ) > -1 || potentialYouTubeVideoSrc.indexOf( 'youtube.com/v/' ) > -1 ) {
return true; } return false;
}
Turn embed objects into iframe objects and ensure they have the right parameters function normalizeYouTubeIframe( youTubeVideo ) {
var a= document.createElement( 'a' );
a.href = youTubeVideo.class='lazy' data-src;
a.hostname = 'www.youtube.com';
a.protocol = document.location.protocol;
var tmpPathname = a.pathname.charAt( 0 ) === '/' ? a.pathname : '/' + a.pathname;
IE10 shim
For security reasons, YouTube wants an origin parameter set that matches our hostname
var origin = window.location.protocol + '%2F%2F' + window.location.hostname + ( window.location.port ? ':' + window.location.port : '' ); if( a.search.indexOf( 'enablejsapi' ) === -1 ) {
a.search = ( a.search.length > 0 ? a.search + '&' : '' ) + 'enablejsapi=1'; }
 // Don't set if testing locally
if( a.search.indexOf( 'origin' ) === -1 && window.location.hostname.indexOf( 'localhost' ) === -1 ) {
a.search = a.search + '&origin=' + origin; }
if( youTubeVideo.type === 'application/x-shockwave-flash' ) {
var newIframe = document.createElement( 'iframe' ); newIframe.height = youTubeVideo.height; newIframe.width = youTubeVideo.width;
tmpPathname = tmpPathname.replace('/v/', '/embed/'); youTubeVideo.parentNode.parentNode.replaceChild( newIframe, youTubeVideo. parentNode );
youTubeVideo = newIframe; }
a.pathname = tmpPathname;
if(youTubeVideo.class='lazy' data-src !== a.href + a.hash) {
youTubeVideo.class='lazy' data-src = a.href + a.hash;
}
return youTubeVideo;
}
Add event handlers for events emitted by the YouTube API function addYouTubeEvents( youTubeIframe ) {
youTubeIframe.pauseFlag = false; new YT.Player( youTubeIframe, {
events: {
onStateChange: function( evt ) { onStateChangeHandler( evt, youTubeIframe ); }
}
} );
}
Returns key/value pairs of percentages: number of seconds to achieve function getMarks(duration) {
var marks = {};
For full support, we're handling Watch to End with percentage viewed if (_config.events[ 'Watch to End' ] ) {
marks[ 'Watch to End' ] = duration * 99 / 100;
}
 
if( _config.percentageTracking ) {
var points = [];
var i;
if( _config.percentageTracking.each ) {
points = points.concat( _config.percentageTracking.each );
}
if( _config.percentageTracking.every ) {
var every = parseInt( _config.percentageTracking.every, 10 ); var num = 100 / every;
for( i = 1; i < num; i++ ) { points.push(i * every); }
}
for(i = 0; i < points.length; i++) {
var _point = points[i];
var _mark = _point + '%';
var _time = duration * _point / 100;
marks[_mark] = Math.floor( _time ); }
}
return marks;
}
function checkCompletion(player, marks, videoId) {
var duration = player.getDuration();
var currentTime = player.getCurrentTime();
var playbackRate = player.getPlaybackRate();
player[videoId] = player[videoId] || {};
var key;
for( key in marks ) {
if( marks[key] <= currentTime && !player[videoId][key] ) { player[videoId][key] = true;
fireAnalyticsEvent( videoId, key ); }
} }

 

Event handler for events emitted from the YouTube API function onStateChangeHandler( evt, youTubeIframe ) {

var stateIndex = evt.data;
var player = evt.target;
var targetVideoUrl = player.getVideoUrl();
var targetVideoId = targetVideoUrl.match( /[?&]v=([^&#]*)/ )[ 1 ];
// Extract the ID
var playerState = player.getPlayerState();
var duration = player.getDuration();
var marks = getMarks(duration);
var playerStatesIndex = {
'1' : 'Play',
'2' : 'Pause'
};
var state = playerStatesIndex[ stateIndex ]; youTubeIframe.playTracker = youTubeIframe.playTracker || {}; if( playerState === 1 && !youTubeIframe.timer ) {
clearInterval(youTubeIframe.timer); youTubeIframe.timer = setInterval(function() {
Check every second to see if we've hit any of our percentage viewed marks checkCompletion(player, marks, youTubeIframe.videoId);
}, 1000);
} else { clearInterval(youTubeIframe.timer); youTubeIframe.timer = false; }
 Playlist edge-case handler if( stateIndex === 1 ) {
youTubeIframe.playTracker[ targetVideoId ] = true; youTubeIframe.videoId = targetVideoId; youTubeIframe.pauseFlag = false; }
 
if( !youTubeIframe.playTracker[ youTubeIframe.videoId ] ) {
This video hasn't started yet, so this is spam return false; }
if( stateIndex === 2 ) {
if( !youTubeIframe.pauseFlag ) {
youTubeIframe.pauseFlag = true;
} else {
// We don't want to fire consecutive pause events return false; }
}
If we're meant to track this event, fire it if( eventsFired[ state ] ) {
fireAnalyticsEvent( youTubeIframe.videoId, state );
} }
Fire an event to Google Analytics or Google Tag Manager function fireAnalyticsEvent( videoId, state ) {
var videoUrl = 'https://www.youtube.com/watch?v=' + videoId;
window[dataLayerName].push({
'event' : 'youTubeTrack',
'attributes': {
'videoUrl': videoUrl,
'videoAction': state }
});
} } )( document, window, { 'events': {
'Play': true,
'Pause': true,
'Watch to End': true
}, 'percentageTracking': {
'every': 25,
'each': [ 10, 90 ]
}
} );
</script>

 

This follows the same model as the scroll listener earlier in the blog. It uses YouTube’s player API to detect changes to the state of the video player as Play, Pause, or Watch to End and pushes an event to the data layer (indicated in bold).

 

It also measures percent completion, which is configurable at breakpoints in a configuration object (the bold section at the end of the code).

 

Each data layer push looks like the following example:

dataLayer.push({
'event' : 'youTubeTrack',
'attributes' : {
'videoURL' : 'https://www.youtube.com/watch?v=msvOUUgv6m8',
'videoAction' : 'Play' }
});

 

The property attributes.videoAction is the state of the video player, while attributes.videoURL is a link directly to the video on YouTube (which also include the video identifier).

 

You can now trigger a tag in Google Tag Manager using a Custom Event of youTube Track and create variables for the data layer properties attributes.videoURL and attributes.videoAction to fill in the Google Analytics event tracking tag’s action and label.

 

Summary

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.

Recommend