/
debugger.js
245 lines (179 loc) · 7.31 KB
/
debugger.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// console formating with "%" only works in Chrome/firefox... dang. fixed!
(function (window) {
'use strict'; // if you say so Mr. Crockford.
// In case the dataLayer_debugger obj does not exist, make it.
if (window.dataLayer_debugger === undefined) {
// Instantiate the main dldb object. (later window.dataLayer_debugger)
var dldb = {
// Cache the dataLayer array.
"dlCache" : window.dataLayer,
// Cache the default dataLayer.push method.
"dotPush" : window.dataLayer.push,
// Acts as the on/of switch for on,off methods or book marklet.
"keepState" : false,
// Counts how many pushes occur.
"pushCount" : window.dataLayer.length || 0,
// time starts when GTM rule is fired or bookmarklet click
"startTime" : new Date(),
// to hold array of callback functions to call inside new .push method
"callbacks" : [],
// Does this debugger off cool logging features?
"coolConsole" : navigator
.userAgent
.toLowerCase()
.match(/chrome|firefox/) ? true : false
};
// Returns time elapsed from startTime.
// Used for timestamping dataLayer.push logs.
dldb.now = function () { return (new Date() - dldb.startTime) / 1000; };
// Returns whether the debugger is on or off.
dldb.state = function () {
return (window.dataLayer_debugger.keepState ? "On" : "Off");
};
// Resets the timer, counter, and/or callbacks depending on arguments.
// No arguments resets all- essentially the same as page refresh.
dldb.validate = function (validKeys, testObj, type) {
var check = [], //obj;
keys = Object.keys(testObj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
for (var j = 0; j < validKeys.length; j++) {
var validKey = validKeys[j];
if (key === validKey){
check.push(validKey);
}
if (key === "transactionProducts" ) {
var products = testObj.transactionProducts;
for (var p = 0; p < products.length; p++) {
var product = products[p];
window.dataLayer_debugger.validate(["name","sku","price","quantity"], product, "product");
}
}
}
}
if (check.length !== validKeys.length){
console.log(validKeys);
//console.log(testObj);
//fix this
//var err = new Error();
//try {
//throw err;
//} catch (err) {
console.log("Invalid " + type + " object pushed to dataLayer. Missing: " + validKeys.join(", ") + " properties.");
//}
return true;
}
return false;
};
// Turns the debugger on by changing the keepState variable,
// changes the dataLayer.push method to add debugging functionality
dldb.on = function () {
dldb.keepState = true;
console.log ("The dataLayer debugger is On");
console.log ("Time is: " + window.dataLayer_debugger.now() + " To reset timer: dataLayer_debugger.reset('time')");
console.dir (window.dataLayer);
// Redefines the dataLayer.push method to add debugging functionality,
// calls (applys) all the functions in the dldb.callbacks array,
// calls the original dataLayer.push methon on all function arguments.
window.dataLayer.push = function () {
for (var a = 0; a < arguments.length; a++) {
var obj = arguments[a],
ks = Object.keys(obj).sort();
// Check for "event" property.
// Put "event" property of pushed object first in list.
for (var v = 0; v < ks.length; v++){
if (ks[v] === 'event'){
ks.unshift(ks.splice(v,1)[0]);
}
}
// try {
dldb.pushCount += 1;
console.group( 'dataLayer.push: #' + dldb.pushCount + ", Time: " + window.dataLayer_debugger.now());
for (var i = 0; i< ks.length; i++) {
var key = ks[i],
val = obj[key],
space = 25 - key.length;
// validate transaction pushes, break if fail
if (key.match(/^transaction(Id|Total|Affiliation|Shipping|Tax|Products)$/)){
if ( window.dataLayer_debugger.validate("transaction", ['transactionTotal','transactionId'], obj, "transaction") ) {
break;
}
}
// validate social pushes, break if fail
if (key.match(/^(network|socialAction|opt_(target|pagePath))$/)){
if ( window.dataLayer_debugger.validate( ['network','socialAction'], obj, "social") ) {
break;
}
}
var logMessage = key + new Array(space).join(' ') + ': ';
if (window.dataLayer_debugger.coolConsole) {
var valType = (typeof(val) === 'object') ? '%O' : '%s';
console.log( logMessage + valType, val);
} else {
console.log( logMessage + (typeof(val) !== 'object' ? val : "") );
if (typeof(val) === 'object') {
console.dir(val);
}
}
}
// } catch (e) {
// console.log("dataLayer error: " + e.message);
// console.log("pushed object was %O", obj);
//}
console.groupEnd();
console.dir(window.dataLayer);
// Call all callbacks within the context of the pushed object.
if (window.dataLayer_debugger.callbacks){
var callbacks = window.dataLayer_debugger.callbacks;
for (var j = 0; j < callbacks.length; j++) {
var callback = callbacks[j];
callback.apply(obj);
}
}
// Calls original cached version of dataLayer.push.
dldb.dotPush(obj);
}
};
};
// Turns debugger off,
// changes dataLayer.push method back to normal.
dldb.off = function () {
dldb.keepState = false;
window.dataLayer = dldb.dlCache;
window.dataLayer.push = dldb.dotPush;
console.log("The dataLayer debugger is " + window.dataLayer_debugger.state() + ".");
console.log("Current time is: " + window.dataLayer_debugger.now());
};
// Set one or many callback functions
// to the debugging version of dataLayer.push method.
dldb.setCallback = function (callback){
window.dataLayer_debugger.callbacks.push(callback);
};
dldb.reset = function () {
for (var r = 0; r < arguments.length; r++){
var arg = arguments[r];
if (arg === "time") {
dldb.startTime = new Date();
} if (arg === "count") {
dldb.pushCount = 0;
} else if (arg === "callbacks") {
dldb.callbacks = [];
} else {
dldb.startTime = new Date();
dldb.pushCount = 0;
dldb.callbacks = [];
}
}
};
window.dataLayer_debugger = dldb;
// In this case the dataLayer_debbugger does exist (after 1st run)
} else {
dldb = window.dataLayer_debugger;
}
// Logic responsible for turning dataLayer_debugger on/off.
if (!window.dataLayer_debugger.keepState) {
window.dataLayer_debugger.on();
} else {
window.dataLayer_debugger.off();
}
}(window));