-
Notifications
You must be signed in to change notification settings - Fork 1
/
tagmanager.js
228 lines (210 loc) · 6.32 KB
/
tagmanager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/* eslint-disable no-undef */
/* jshint esversion: 8 */
const tagManager = Object.create(null);
tagManager.tags = [];
tagManager.logs = [];
tagManager.runLogs = [];
tagManager.lastParams = {};
tagManager.debug = false;
tagManager.lastRun = 0;
tagManager.accounts = {};
// Default variables
tagManager.variables = {
get path() {
return window.location.pathname;
},
get title() {
return document.title;
},
get referrer() {
return document.referrer;
},
get origin() {
return window.location.origin;
},
get hash() {
return window.location.hash.substring(1);
},
param(urlParam) {
const params = new URLSearchParams(window.location.search);
if (params.has(urlParam)) {
return params.get(urlParam);
}
return "";
},
form(cssSelector) {
const formEl = document.querySelector(cssSelector);
const fData = new FormData(formEl);
let formObject = {};
for (const pair of fData.entries()) {
formObject[pair[0]] = pair[1];
}
return formObject;
},
now: {
date: new Date().toJSON().split('T')[0],
year: new Date().getFullYear(),
month: new Date().getMonth() + 1,
day: new Date().getDate(),
weekday: new Date().getDay(),
hour: new Date().getHours(),
minute: new Date().getMinutes(),
timezoneOffset: new Date().getTimezoneOffset() / 60,
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
},
getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
},
setCookie(name, value, exp = 5) {
const date = new Date();
date.setTime(date.getTime() + exp * 24 * 60 * 60 * 1000);
document.cookie = `${name}=${value}; Path=/; SameSite=Lax; expires=${date.toUTCString()}`;
},
deleteCookie(name) {
document.cookie = `${name}=; Path=/; SameSite=Lax; expires=Thu, 01 Jan 1999 00:00:10 GMT;`;
}
};
// Obtaining consent status. This method shoud be updated with the actual consent mechanism.
tagManager.consent = {
_essential: true,
_analytics: false,
_advertising: false,
get essential() {
return this._essential;
},
set essential(value) {
if (typeof (value) === "boolean") {
this._essential = value;
}
},
get analytics() {
return this._analytics;
},
set analytics(value) {
if (typeof (value) === "boolean") {
this._analytics = value;
}
},
get advertising() {
return this._advertising;
},
set advertising(value) {
if (typeof (value) === "boolean") {
this._advertising = value;
}
}
};
// Create an URL with parameters from an object
tagManager.addUrlParameters = function (baseUrl, params) {
const url = new URL(baseUrl);
const searchParams = new URLSearchParams(url.search);
Object.entries(params).forEach(([key, value]) => {
searchParams.append(key, value);
});
url.search = searchParams.toString();
return url.toString();
};
// Creates an image pixel
tagManager.imagePixel = function (imageURL, params = {}) {
let pixel = document.createElement("img");
pixel.src = this.addUrlParameters(imageURL, params);
pixel.width = "1";
pixel.height = "1";
pixel.style.position = "absolute";
pixel.style.left = "-5px";
pixel.style.top = "0px";
document.body.appendChild(pixel);
};
// Creates a cookieless image pixel
tagManager.cookieLessImagePixel = function (baseUrl, params = {}) {
const url = this.addUrlParameters(baseUrl, params);
const pixelSrc = `<img src='${url}' />`;
const pc = document.createElement("iframe");
pc.width = 1;
pc.height = 1;
pc.role = "img";
pc.frameBorder = "0";
pc.sandbox = "";
pc.srcdoc = pixelSrc;
document.body.appendChild(pc);
};
// Add html to the body
tagManager.addHtml = function (html, appendTo = document.body) {
const node = document.createRange().createContextualFragment(html);
appendTo.append(node);
};
// Adds a tag function to the list of tags
tagManager.tag = function (fun) {
this.tags.push(fun);
};
// Executes all the tags with the params
tagManager.run = function (params) {
this.runLogs.push(params);
Object.assign(this.lastParams, params);
this.tags.forEach(element => {
element(params);
});
};
// Allows using triggers
tagManager.trigger = function (eventName, cssSelector = "", paramsObj = {}) {
// eslint-disable-next-line no-unused-vars
const self = this;
let proced;
if (typeof (paramsObj) === "object") {
proced = function () {
dataLayer.push(paramsObj);
};
} else if (typeof (paramsObj) === "function") {
proced = paramsObj;
} else {
throw ("Trigger's third param must be either an object or a function");
}
if (cssSelector === "") {
window.addEventListener(eventName, proced);
return true;
}
const list = document.querySelectorAll(cssSelector);
if (list.length === 0) {
return false;
}
for (let el of list) {
el.addEventListener(eventName, proced);
}
};
// Loops trough dataLayer and runs each element trough all the tags
tagManager.parseDL = function () {
let n = this.lastRun;
while (n < dataLayer.length) {
this.run(dataLayer[n]);
n = n + 1;
this.lastRun = n;
}
};
// Starts watching for changes in dataLayer
tagManager.start = function () {
this.parseDL();
setInterval(() => {
this.parseDL();
}, 500);
};
// Default tag for testing/debugging
tagManager.tag(function logs_params(params) {
if (tagManager.debug) {
console.log("tagManager params are: ", params);
}
});
// Default trigger: when the dom is ready (html, css and javascript loaded)
tagManager.trigger("DOMContentLoaded", "", {
"event": "DOM ready"
});
// Default trigger: when the page is completeley loaded (images, css, javascript and other resources)
tagManager.trigger("load", "", {
"event": "Window loaded"
});
// Default trigger: when the location.hash in the URL changes
tagManager.trigger("hashchange", "", {
"event": "Hash changed",
"hash": tagManager.variables.hash
});