1. Home
  2. Docs
  3. Google Tag Manager Guide
  4. Google Tag Manager Basic
  5. Variables Guide in Google Tag Manager—User-Defined Variables

Variables Guide in Google Tag Manager—User-Defined Variables

Variables in Google Tag Manager are named placeholders for values that are populated when code is run on your website or mobile app. Tag Manager provides a set of predefined built-in variables. Built-in variables handle most needs for tag and trigger configurations. You can also create user-defined variables for web pages or mobile apps to suit specific requirements that might not be covered by built-in variables.

In this section, we mainly talk about User-Defined Variables. Create custom user-defined web variables in Google Tag Manager to suit specific requirements that might not already be covered by built-in variables.User-Defined Variables provides a total of 18 variables in 5 types.

Let’s introduce them one by one:

Navigation

There are two types of Navigation: HTTP Referral and URL. The former is the source of the upper page and the latter is the current page URL.

Variables Guide in Google Tag Manager—User-Defined Variables

 

HTTP Referrer

The value is set to the HTTP referer, which is the URL of the previous page that the person visited. For example, if a person navigates to one of your product pages from the home page, the referrer will be the home page. An instance of this variable type is automatically created by Tag Manager, but you can create additional instances if you would like to have expose different parts of the referrer URL.

We can directly enter document.referral in the console of developer tools to get HTTP Referral:

Variables Guide in Google Tag Manager—User-Defined Variables

There are seven component types of HTTP Referrer. These Component Types are different splits for HTTP Referrer:Assume that the HTTP Referral is https://www.google.com/test/search:443?q=Google+analytics&btnK=Google+Search#summary, then each Component Type is as follows:

Component Types Value
Full URL Returns the full URL without the hash fragment
Eg:https://www.google.com/test/search:443?q=Google+analytics&btnK=Google+Search
Protocol Returns the protocol of the URL,Usually http or https
Eg:https
Host Name Returns the hostname of the URL without the port number
Eg:www.google.com
Port Returns the port number used in the URL,Generally http is 80, https is 443
Eg:443
Path Returns only the path name in the URL
Eg:/test/
Query Returns the entire query parameter string 
Eg:q corresponds to Google analytics, btnK corresponds to Google Search
Fragment Returns the value after #
Eg:summary

 

Eg:The following configuration represents the host name of Referral:

Variables Guide in Google Tag Manager—User-Defined Variables

 

URL

This type of variable allows you to parse and expose URL components. You can create additional instances to expose different parts of the URL. The URL components you can choose from are: Full URL, Protocol, Hostname, Port, Path, Filename Extension, Query, and Fragment. The input value set for variables of this type is the URL of the current page the user is on (retrieved from document.location). Adjust URL Source to tell Tag Manager to use another variable as the source of the URL value.

Assuming the URL is https://www.bbccss.com/docs/google-tag-manager/chap2/scroll-depth:443?gclid=1234#set-trigger, Each Component Type corresponds to:

Component Types Value
Full URL Returns the full URL without the hash fragment
Eg:https://www.bbccss.com/docs/google-tag-manager/chap2/scroll-depth:443?gclid=1234
Protocol Returns the protocol of the URL,Usually http or https
Eg:https
Host Name Returns the hostname of the URL without the port number
Eg:www.bbccss.com
Port Returns the port number used in the URL,Generally http is 80, https is 443
Eg:443
Path Returns only the path name in the URL
Eg:/docs/google-tag-manager/chap2/scroll-depth
Filename Extension I haven’t used it yet.
Query Returns the entire query parameter string 
Eg: gclid corresponds to 1234
Fragment Returns the value after #
Eg:set-trigger

 

Page Variables

Page Variables has 5 types of variables:

Variables Guide in Google Tag Manager—User-Defined Variables

 

1st Party Cookie

This value is set to the value of the 1st party cookie with the name of the domain that the user is currently on. If more than one cookie with same name is deployed on the same domain, the first value will be chosen. This value is the same is if you had called document.cookie from within a page and chosen the first result.

Assuming the client ID cookie on the blog is _ga:

Variables Guide in Google Tag Manager—User-Defined Variables

 

Client ID can be obtained by setting this in the cookie variable:

Variables Guide in Google Tag Manager—User-Defined Variables

 

 

Custom JavaScript

The value is set to the result of a JavaScript function. The JavaScript must take the form of an anonymous function that returns a value. For example, a custom JavaScript variable can be created to convert all instances of the predefined {{url}} variable to lowercase:

function () {
return {{url}}.toLowerCase();
}

 

You can customize some JavaScript variables to process or get data. For example, in Bulk Event Tracking——ga-data Method ,we use a piece of JavaScript to get the ga-data attribute of the page. The code is as follows:

<span style="font-size: 12pt;">function() {
	var elem = {{element}},
	    attr = "ga-data", // change this to the attribute that you want to get
        result = (elem.getAttribute && elem.getAttribute(attr)) || null;
 
	if( !result ) {
		var attrs = elem.attributes,
			l = attrs.length;
		for(var i = 0; i < l; i++) {
			if(attrs[i].nodeName === attr)
				result = attrs[i].nodeValue;
                }
	}
 
	return result;
}</span>

 

 

Data Layer

The value is set when data is pushed to the data layer via the dataLayer.push() call:
dataLayer.push({"Data Layer Name": "value"}).

You can specify how Tag Manager interprets dots (“.“) in the key name:

  • Version 1: allow dots in key names. For example, for dataLayer.push("a.b.c": "value"), interpret the name of the key as “a.b.c” (i.e. {"a.b.c": "value"}).
  • Version 2: interpret dots as nested values. For example, interpret dataLayer.push({"a.b.c": "value"}) as three nested levels: {a: {b: {c: "value"}}}

Usually there is an event in the data layer, which can be triggered by custom events to get the data of the data layer variables.The code structure is as follows:

dataLayer.push({
  'color': 'red',
  'conversionValue': 50,
  'event': 'customizeCar'
});

The event is received using the custom event in the trigger; color and conversion are received using data layer variables. The configuration of color is as follows:

Variables Guide in Google Tag Manager—User-Defined Variables

Pay attention to case, which is case sensitive.

 

JavaScript variable

The value is set to the global JavaScript variable you specify. If the value required was not set up in the data layer (see Data Layer variable), and it’s not visible in the DOM (see also: DOM Element variable), it might be possible to get the value from a JavaScript variable. Use this variable type if you can find the value in the page’s source code as a global JavaScript variable.

Global JavaScript variable, is actually a js variable, with a structure like:

<script>
      var userid="haran.huang@ichdata.com;
</script>

The userid can be obtained by setting this in the variable:

Variables Guide in Google Tag Manager—User-Defined Variables

Undefined Value

Contains the JavaScript ‘undefined’ value. No settings required.
Variables Guide in Google Tag Manager—User-Defined Variables

Page Elements

There are three types of Page Elements:

Variables Guide in Google Tag Manager—User-Defined Variables

Auto-Event Variable

Captures information about an item that triggered an event (e.g. clicks, form submissions, element visibility, etc.)

  • Element: Returns the element object. Can be treated like an object for custom JavaScript, e.g. {{Element}}.title, or in CSS selectors, e.g. {{Element}} matches CSS Selector div.foo.
  • Element Type: Returns the value element.tagName, e.g. “A”, “BUTTON”, “IMG”.
  • Element Attribute: Specify an attribute name and this option will return the value of that attribute.
  • Element Classes: Returns the list of classes found in the element’s class attribute.
  • Element ID: Returns the value of the id attribute.
  • Element Target: Returns the value of the target attribute, e.g. “_blank”.
  • Element Text: Returns the value of the text content of the element.
  • Element URL: Returns the URL of the element, gathered from the href or action attribute.
  • History New URL Fragment: Returns the new URL fragment from browser history, e.g. “#summary”.
  • History Old URL Fragment: Returns the old URL fragment from browser history, e.g. “#intro“.
  • History New State: The new history state object, controlled by the site’s calls to pushState.
  • History Old State: The old history state object, controlled by the site’s calls to pushState.
  • History Change Source: Returns the event that caused a history change, e.g. “pushState”, “replaceState“, etc.

The configuration page is as follows, simple settings can be used:

Variables Guide in Google Tag Manager—User-Defined Variables

 

 

DOM Element

The value is set to the text of the DOM (Document Object Model) element or the value of the specified DOM element attribute. If the desired value is not set up in the data layer (see Data Layer variable), it’s possible that the value can be retrieved from the DOM. Use this variable type if you can find the value in the DOM.

If the optional attribute name is set, the variable’s value will return the value specified from that attribute (e.g. data-food="cupcake"); otherwise, the value will be the text within the DOM element.

You can use this method to obtain the attribute information on the page. It can be used when the amount of data is small, and it is recommended to use the data layer when the amount of data is large.

The setting interface is as follows…

Variables Guide in Google Tag Manager—User-Defined Variables

There are two positioning methods, Id and CSS selectors. For this precise positioning, forget to track and transmit a small amount of data.Otherwise you need to structure the data on the page first. If you really need to do this, you might as well use the data layer.

 

Element Visibility

The value is set based on the visible state of the specified DOM element. Unlike the Element Visibility trigger, a single Element Visibility variable can only report the visibility of a single element. Choose whether to select an element based on the element ID or a CSS Selector. If multiple elements are matched by a specified CSS Selector, the first matched element will be used.

You can choose the output type for this variable:

  • True / False: A boolean value that indicates whether the selected element is visible when the variable is referenced. 
  • Percent: A percentage value between 0 and 100 that indicates how much of the selected element is visible on screen when the variable is referenced.

If you select True / False as the output type, you can also specify Minimum Percent Visible to indicate how much of the selected element must be visible on screen for the variable to return true

 

The role of this is to control the visibility of page elements, but generally it is better to control than the direct source code.

Utilities

Utilities has seven types of variables.

Variables Guide in Google Tag Manager—User-Defined Variables

Constant

The value is set to a string you provide. Constant string variables are commonly used when there are multiple tags that use the same account number. See also: Google Analytics Settings.

For example, Tracking Id uses a constant to store, and this constant is directly referenced later.

Variables Guide in Google Tag Manager—User-Defined Variables

If you have a fixed value, you can store it through a constant, so if you want to modify it later, you only need to modify the constant in one place.

 

Custom Event

The value is set to the name of the custom event that was pushed to the data layer.  The value is set to “eventNameXYZ” when the following code on your website is executed:   dataLayer.push({‘event’: ‘eventNameXYZ’});

 

Environment Name

Returns the name of the environment that is viewed in preview mode. The value is the name of the environment link via which the container may have been loaded (e.g. “Live”).

 

Google Analytics Settings

The Google Analytics Settings variable is used in Universal Analytics tags in web and mobile (Firebase) containers to centrally configure and share common Google Analytics settings that are used across multiple tags. When you create a Google Analytics tag using Universal Analytics, Tag Manager will prompt you to select or create a Google Analytics Settings variable. 

The basic settings of the previous tags are too long. Each time you set a tag, you have to set a lot of the same information repeatedly. The efficiency is very low, so Google Analytics Settings appears. The purpose of this is to introduce the common basic settings as variables. It’s a lot easier.

The usage of Google Analytics Settings is more diverse. I will write a separate one later. Here is one of my Google Analytics Settings settings:

Variables Guide in Google Tag Manager—User-Defined Variables

 

Lookup Table

The value is set according to the instructions in the lookup table. The lookup table contains two columns. (Table is empty to illustrate how data is used later):

When [select variable] equals Set [this variable] to

The Lookup Table allows you to create a variable for which the value varies according to the value of another variable. This is useful if your website is set up in such a way that the appropriate value (for example, a conversion ID) can be mapped to the URL, DOM element, or other part of the page. In this example, a variable named Conversion ID is created. If the URL contains “/thanks/buy1.html”, the value is set to “12345”; if the URL contains “thanks/buy2.html”, the value is set to “34567”.

When {{url}} contains Set {{Conversion ID}} to
/thanks/buy1.html 12345
/thanks/buy2.html 34567
/thanks/buy3.html 56789

Random Number

The value is set to a random number between 0 and 2147483647.

 

RegEx Table

A RegEx Table variable is similar to a Lookup Table variable, with the addition of being able to run regular expression patterns for the items you want to match.

For this RegEx Table configuration:

Pattern Output
.*/page[1-3]\.html.* foo
.*/page[4-6]\.html.* bar
.*/page[7-9]\.html.* baz

The output value of the variable will be as follows:

Matched result Value
http://example.com/page1.html foo
http://www.example.com/page1.html foo
http://example.com/page2.html#detail foo
http://example.com/page5.html bar
http://example.com/page5.html?status=new bar
http://example.com/page6.html bar
https://example.com/page9.html baz

RegEx Table lookups run from the top of the list to the bottom. When a match is found, the corresponding output value is returned.

Select Set Default Value to set an output value for when a match is not found.

By default, patterns must match the full input string and are case insensitive. This behavior can be adjusted in Advanced Settings:

  • Ignore Case: Patterns will match uppercase and lowercase matches without having to build this into the regular expression explicitly.
  • Full Matches Only: If enabled, patterns must match the entire input. This is equivalent to having start (^) and end ($) anchors implicitly around your pattern. If disabled, patterns will match when they are found anywhere in the input.
  • Capture Groups and Replace Functionality: If enabled, you can use dollar-sign replacement syntax to include portions of the input (e.g. from capturing groups in the matched pattern) within the output. For example, if the matched regular expression is /(news)/page(2)\.html, you can use $1 to reference the first capture group (“news“) and $2 to reference the second capture group (“2“).

 

 

 

Container Data

Container Data has three variables:

Variables Guide in Google Tag Manager—User-Defined Variables

Container ID

Returns the ID of the Tag Manager container, e.g. ‘GTM-PHXQ69M’.

 

Version Number

When the container is in preview mode, the container version variable returns the container’s preview version number. Otherwise, this variable returns the container’s live version number.

Variables Guide in Google Tag Manager—User-Defined Variables

 

 

Debug Mode

The value is set to true if the container is in preview and debug mode, and false if not.

 


If you don't understand, You can leave a comment below or email me (haran.huang@ichdata.com).
Tags , ,
Was this article helpful to you? Yes No

How can we help?

Post my comment
Cancel comment
Expression Texture Bold Strikethrough Center Italic Sign in

Hi, you need to fill in your nickname and email!

  • Nickname (required)
  • Email (required)
  • Website