- Technical Reference
Easy Collect para o Google Tag Manager
This document introduces the APIs and functionality developed to support Google Tag Manager (GTM). Some settings on the tool's side are important so that the code implemented in the Easy Collect tag has the expected behavior. More details about here.
The options
object contains the global Easy Collect settings. The default values will work in most cases, so they should be changed carefully and consciously.
var options = {
helperName: 'easyCollect',
dataLayerName: 'dataLayer',
debug: ({{Debug Mode}} || false),
waitQueue: true,
containerId: ({{Container ID}} || ''),
exceptionEvent: 'gtm_dataQuality_event',
exceptionCategory: 'GTM Exception',
customNamePageview: 'ga_pageview',
customNameEvent: 'ga_event',
customNameTiming: 'ga_timing',
errorSampleRate: 1
};
Use this optional function to start Easy Collect with options other than the default ones. It takes as an argument the opt_options
object, which has the following keys:
-
helperName
-- By default"easyCollect"
. A string that identifies the name of the Easy Collect instance in the window object of the browser. Tagging is not affected by changing this value if done by thesafeFn
function (recommended). -
dataLayerName
-- By default"dataLayer"
. A string that identifies the name of the data layer instance in the browser's window object. It must be the same value set in the snippet of the GTM in order for the Easy Collect interface functions (eggetDataLayer
) to work. -
debug
-- By default this is the GTM variable{{Debug Mode}}
. If disabled, it isfalse
. A boolean that signals to Easy Collect whether the current context is debug or production. If true, events will be triggered only viaconsole.log
, without sending them to GA. -
waitQueue
-- Default istrue
A boolean that signals to Easy Collect whether it should use a queue on events. If true, all events will be stacked in an internal structure until the first pageview on the page occurs. We recommend that this option is always enabled, as it avoids inconsistencies in Google Analytics reports. -
containerId
-- By default this is the GTM variable{{Container ID}}
. If disabled, it is the empty string''
. A string that should match the ID of the GTM container where Easy Collect was configured (GTM-XXXXX). -
exceptionEvent
-- By default"gtm_dataQuality_event"
. A string that identifies the event sent to the data layer if an exception occurs in the GTM code. This option supports the idea of collecting for a Google Analytics property of Quality Assurance . To better understand the use of this configuration, see GTM configuration documentation. -
exceptionCategory
-- By default"GTM Exception"
. A string that indicates which value should be filled in the"event_category"
key of the event sent to the data layer in case an exception occurs in the GTM code. This option supports the idea of collecting for a Google Analytics property of Quality Assurance . To better understand the usage of this configuration, see GTM configuration documentation -
customNamePageview
-- By default"ga_pageview"
. The string that identifies the event sent to the data layer each time thepageview
function (see below) is called. -
customNameEvent
-- By default"ga_event"
. A string that identifies the event sent to the data layer each time theevent
function (see below) is called. -
customNameTiming
-- By default"ga_timing"
. A string that identifies the timing event sent to the data layer each time thetiming
function (see below) is called. -
errorSampleRate
-- By default1
. Must be an integer between 0 and 1, which controls the sampling level of errors sent to the GA of Data Quality (more details to be added). It is used to control the collection in environments where the volume of shots is very large.
The following functions have specificities for collecting data based on GA and GTM tools. Because of this, the internal functions of this API use the variable created by GTM called dataLayer
. To ensure that the functionalities of the functions are correct, it will be necessary to ensure that the environment in question has the data layer correctly initialized.
Used to trigger custom pageview.
path
(optional): String that receives the path of the custom Pageview.object
(optional): Object that will be assigned to the pageview. It can be used to pass Enhanced Ecommerce objects, as well as custom metrics and dimensions. Any custom key will be pushed into the dataLayer.
easyCollect.pageview('/post/finished-reading', {
area: 'Open',
categoria: 'Data Science'
});
Used to trigger events.
category
: String representing the event category.action
: String representing the action of the event.label
(optional): String that can represent the event label.object
(optional): Object that will be assigned to the event. It can be used to pass Enhanced Ecommerce objects, as well as custom metrics and dimensions. Any custom key will be pushed into the dataLayer.
Important: The value key can be passed either as the fourth value of the call or as a parameter of the object "object"
.
easyCollect.event('MyCategory', 'MyAction', 'MyLabel', 0, {
city: 'São Paulo'
});
easyCollect.event('MyCategory', 'MyAction', 'MyLabel', {
eventValue: 0,
city: 'São Paulo'
});
Returns any object contained in the dataLayer exposed in the environment. This function is an encapsulation of the GTM macro .get().
key
: String representing the key of the object to be retrieved.
- ANY: The value retrieved from the GTM data model.
dataLayer.push({
myObject: 'value',
myOtherObject: 'otherValue'
});
easyCollect.getDataLayer('myObject'); // value
Finds an object or value by the given key. If any of the keys in the chain does not exist, the function returns undefined, thus avoiding throwing errors.
key
: String representing the key of the object to be foundopt_root
(Optional): Object that has the key to find. By default it iswindow
.
- ANY: The value retrieved from the data model of the given variable.
var object = {
myObject: {
myArray: [
{
myKey: 'found my value'
}
]
}
};
easyCollect.getKey('object.myObject.myArray.0.myKey'); // found my value
easyCollect.getKey('myObject.myArray.0.myKey', object); // found my value
easyCollect.getKey('chaveNaoExistente.myArray.0.myKey', object); // undefined
Returns text without special characters, accents, spaces or capital letters (optionally).
text
: String to be treatedopts
(optional): Object with variables to configure the sanitize function. _capitalized
: Defines the way the String will be treated. - true: Put the String as Camel Case; - false: Sets the String as Snake Case. _spacer
: Defines which text will be used as a separator in place of_
.
- String: The value received by parameter and modified by the function.
easyCollect.sanitize('My Disorganized String'); // my_disorganized_string
easyCollect.sanitize('My Disorganized String', { capitalized: true }); // MyDisorganizedString
easyCollect.sanitize('My Disorganized String', { spacer: '-' }); // my-disorganized-string
easyCollect.sanitize('My Disorganized String', {
capitalized: true,
spacer: '-'
}); // My-Disorganized-String
Creates a cookie or returns its value based on the Parameters received in the function.
name
: String representing the name of the cookie;value
: String representing the value of the cookie;opts
(optional): Object with variables to configure the cookie function:exdays
(optional): Numeric representing the number of days for the cookie to expire;domain
: (optional): String representing the domain to which the cookie should be assigned;path
(optional): String representing the website path to which the cookie should be assigned;
- String: complete value of the created or retrieved cookie.
easyCollect.cookie('myCookie', 'myValue', {
exdays: 3, // Expire days
domain: '.mydomain.com.br', // Domain that the cookie assigned
path: '/my-path' // Cookie path
}); // myCookie=myValue; expires=Sun, 16 Oct 2016 19:18:17 GMT; domain=.mydomain.com.br; path=/my-path
easyCollect.cookie('myCookie'); // myValue
Easy Collect safe function. The main concept behind its use is to guarantee that data collection does not interfere with the natural behavior of the portal when it is used, avoiding leakage of logs and errors to the environment in question.
To make this proposal effective, the function receives a parameter callback. Within the scope of this callback, it is possible to receive a parameter object with extended Easy Collect functions, in order to guarantee the encapsulation of sensitive functions. This object will be represented from now on as "Internal Easy Collect" (more details in the next section).
id
: It must receive the name of the tag (from the GTM) in which the code in question is contained.callback
: Callback function that scopes to the safeFn environment. Pass via parameter the Internal Easy Collect for use.immediate
(Optional): Boolean variable, which by default (true) executes the callback function immediately. If false, the function's return will be the safe function itself, which must be executed manually when necessary.
- Function or undefined: If the
immediate
parameter receives the value true, safeFn executes the callback and returns undefined. But if theimmediate
parameter has the value false, the return is the callback function itself to be executed later.
easyCollect.safeFn('GTM Tag Name', function(collect) {
collect.event('MyCategory', 'MyAction', 'MyLabel', 'Meuvalue', {
dimension1: 'São Paulo'
});
});
var fn = easyCollect.safefn(
'GTM Tag Name',
function(collect) {
console.log(new Date());
},
{ immediate: false }
);
setTimeout(fn, 2000);
The safeFn
function has a specific treatment for Exceptions that occur within its safe scope. Using the Easy Collect customization variables options.debug, options.exceptionEvent, options.exceptionCategory and options.errorSampleRate, the function assigns valuees to the GTM dataLayer, which will use the GTM configuration to send events to Google Analytics. This practice is based on the design of Quality Assurance.
Object with built-in functions passed via parameter in the safeFn
function callback.
The on
method is used to execute a callback when executing some event in a specific HTML element. In case there is no jQuery on the page, it is based on the querySelectorAll javascript function, and because of that, it is necessary to pay attention to browser compatibility. It is not recommended to use this function on pages that support IE 7 or lower.
The presence of the fourth argument, parent
, transforms the functionality of the on
method into that of the delegate
method.
-
event
: String of the event that will execute the callback, examples: 'mousedown', 'click', etc. Learn more. -
selector
: CSS Selector String that will fetch the elements that will execute the callback in the event firing. Learn More. -
callback
: Function executed on triggering the event supplied in theevent
parameter. -
parent
(optional): Root element from where the event should be heard.
easyCollect.safeFn('Tag Name', function(collect) {
collect.on('mousedown', '#buttonX', function(collect) {
collect.event('MyCategory', 'MyAction', 'MyLabel');
});
});
easyCollect.safeFn('Tag Name', function(collect) {
collect.on(
'mousedown',
'#buttonX',
function(collect) {
collect.event('MyCategory', 'MyAction', 'MyLabel');
},
'#boxY'
);
});
The delegate
method is used to execute a callback when executing some event on a specific HTML element. Unlike on
, it defaults to binding the event to the document.body
and not to the selector passed in the selector
argument, waiting for any event that occurs on an element that matches the selector
argument. .
This method is preferable against the on
method in cases where the element does not already exist on the page or when it may exist and cease to exist depending on the user's navigation, such as options from a drop-down menu or an infinite scrolling list.
-
event
: String of the event that will execute the callback, examples: 'mousedown', 'click', etc. Learn more. -
selector
: CSS Selector String to which the elements that trigger thebody
event should be compared. Learn More. -
callback
: Function executed on triggering the event supplied in theevent
parameter.
easyCollect.safeFn('Tag Name', function(collect) {
collect.delegate('mousedown', '#buttonX', function(collect) {
collect.event('MyCategory', 'MyAction', 'MyLabel');
});
});
// Equivalente a
easyCollect.safeFn('Tag Name', function(collect) {
collect.on(
'mousedown',
'#buttonX',
function(collect) {
collect.event('MyCategory', 'MyAction', 'MyLabel');
},
document.body
);
});
The wrap
function provides several facilitating functions for interactions with the DOM in order to standardize and make data collection compatible in environments without the concept of data layer. The motivation for the elaboration of this function is the non-dependence of market libraries, such as jQuery, in order not to depend on their installation in tagged environments. When executing the function, an object with the facilitating functions will be returned.
elm
String, HTML element or Array of HTML elements.- String: the text is used as a CSS selector, creating an encapsulation with all the elements that cross the selector.
- HTML Element, NodeList or array of HTML Elements: the supplied elements will be used as a base for the encapsulation.
- Object: Encapsulation with facilitating functions.
// Apenas um elemento
easyCollect.safeFn('Tag Name', function(collect) {
collect.on('mousedown', '#buttonX', function() {
var text = collect.wrap(this).text({ sanitize: true });
collect.event('Category', 'Action', 'Label_' + text);
});
});
// Múltiplos elementos
easyCollect.safeFn('Tag Name', function(collect) {
var urls = collect.wrap('a');
console.log(urls.nodes); // Array of nodes a.
});
Object generated by the wrap function, includes several functions that help in DOM manipulation. The facilitating functions contained in this object aim to reduce JavaScript code verbosity and avoid the use of libraries dependent on tagged environments.
Array of HTML elements or NodeList that will be the basis of the functions.
Function that checks if the HTML element has the class passed by parameter.
-
className
: String of the name of the class to be matched with the element. -
opts
(optional): Object with variables for setting the hasClass function. *toArray
: If the value is true, returns the array of results related to the comparison.
- Boolean or Array of Boolean: If the
opts
parameter is informed with thetoArray
attribute receiving the value true, the function will return the array or boolean of found elements. If only theclassName
parameter is informed, the function returns true or false whether or not it finds an element with the specified class.
easyCollect.safeFn('Tag Name', function(collect) {
collect.on('mousedown', '.button', function() {
if (collect.wrap(this).hasClass('myClass')) {
collect.event('MyCategory', 'MyAction', 'MyLabel');
}
});
});
A wrapper around the Native Console. Created to ensure it runs only during Debug Mode and only if console[type] exists.
-
type
Type of console to be realized. Can be any type supported by the console:log
,warn
,error
,table
,group
... -
message
Text to be sent to the console. -
object
(optional): Any object with more details than should be sent to the chosen method.
- undefined: No return is sent or should be expected after executing this function.
easyCollect.safeFn('Tag Name', function(collect) {
collect.on('mousedown', '.button', function() {
if (collect.wrap(this).hasClass('myClass')) {
collect.event('MyCategory', 'MyAction', 'MyLabel');
} else {
collect.log('log', 'Class "myClass" not found');
}
});
});
Function that checks if the HTML element matches the selector.
-
selector
String of the selector to be matched with the element. -
opts
(optional): Object with variables for setting the matches function. *toArray
: If the value is true, returns the array of results related to the comparison.
- Boolean or Array of Boolean: If the
opts
parameter is informed with thetoArray
attribute receiving the value true, the function will return the array or boolean of found elements. If only theselector
parameter is informed, the function returns true or false whether or not it finds an element with the specified class.
easyCollect.safeFn('Tag Name', function(collect) {
collect.on('mousedown', '.button', function() {
if (collect.wrap(this).matches('.myForm .button')) {
collect.event('MyCategory', 'MyAction', 'MyLabel');
}
});
});
For each element in the set, get the first element that matches the selector by testing the element itself and traversing its ancestors in the [DOM] tree(https://developer.mozilla.org/en-US/docs/Web/API /Document_Object_Model).
selector
: CSS selector string that will match the HTML element.
- Wrap: An encapsulation with the elements that match the selected selector.
easyCollect.safeFn('Tag Name', function(collect) {
collect.on('mousedown', '.button', function() {
var text = collect
.wrap(this)
.closest('div.parentDivWithText')
.text({ sanitize: true, onlyFirst: true });
collect.event('MyCategory', 'MyAction', 'MyLabel' + text);
});
});
Function that returns the text of the element.
opt
: Object with variables to configure the text function.sanitize
: If booleantrue
, will use sanitize with default options. If it is an object, it will pass the chosen options to the internal sanitize.onlyFirst
: Boolean that in case of true returns only the direct text of the element and not of all its children.onlyText
: Boolean that in case of true returns the concatenated text instead of an array of Strings.
easyCollect.safeFn('Tag Name', function(collect) {
var text = collect
.wrap('#myId')
.text({ sanitize: true, onlyFirst: true, onlyText: true });
var text2 = collect
.wrap('#myOtherId')
.text({ sanitize: { spacer: '/', capitalized: false } });
collect.pageview('/' + text + '/' + text2);
});
Function that returns a Wrap object of all elements that match the selector.
sel
: String of the CSS selector that will match the HTML element.
easyCollect.safeFn('Tag Name', function(collect) {
var text = collect
.wrap('#myId')
.find('.myClass')
.text({ sanitize: true });
collect.pageview('/' + text);
});
Function that executes code for each element. It has the same behavior as the Map API.
-
func
: Function to be executed, it can receive a parameter that will be the reference of the iterated element. -
params
: Array of Parameters used in the function.
easyCollect.safeFn('Tag Name', function(collect) {
var sources = collect.wrap('img').map(function(elm) {
return elm.src;
});
console.log(sources); // Array with the src attribute values of each img element
});
Compression | Size (KB) |
---|---|
No compression | 14.71 |
Minified by GTM | 7.14 |
With GZip | 2.72 |
DP6 Koopas !!!