forked from keen/common-web
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon-web.js
More file actions
437 lines (319 loc) · 12 KB
/
common-web.js
File metadata and controls
437 lines (319 loc) · 12 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
(function () {
var options = {
pageviewsEventName: "pageviews",
inputChangeEventName: "input-changes",
clicksEventName: "clicks",
formSubmissionsEventName: "form-submissions",
callbackTimeout: 1000,
globalProperties: {
page_url: window.location.href,
referrer_url: document.referrer
}
};
// create a common namespace with options
var CommonWeb = {
options: options
};
CommonWeb.addGlobalProperties = function(properties) {
$.extend(CommonWeb.options.globalProperties, properties);
}
// initiate user tracking, using a GUID stored in a cookie
// The user can pass in a custom cookie name and custom GUID, if they would like
CommonWeb.trackSession = function(cookieName, defaultGuid) {
if(typeof(cookieName) !== "string") {
cookieName = "common_web_guid";
}
// Look for the GUID in the currently set cookies
var cookies = document.cookie.split('; ');
var guid = null;
for(var i=0; i < cookies.length; i++) {
cookieParts = cookies[i].split('=')
if(cookieParts[0] === cookieName) {
// Got it!
guid = cookieParts[1];
break;
}
}
// We didn't find our guid in the cookies, so we need to generate our own
if(guid === null) {
if(typeof(defaultGuid) === "string") {
guid = defaultGuid;
} else {
genSub = function() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
guid = genSub() + genSub() + "-" + genSub() + "-" +
genSub() + "-" + genSub() + "-" + genSub() + genSub() + genSub();
}
expiration_date = new Date();
expiration_date.setFullYear(expiration_date.getFullYear() + 1);
cookie_string = cookieName + "=" + guid + "; path/; expires=" + expiration_date.toGMTString();
document.cookie = cookie_string
}
CommonWeb.addGlobalProperties({guid: guid});
return guid;
}
// setup pageview tracking hooks, optionally including more properties
// more properties can also be a function
// do not double set along with track!
CommonWeb.trackPageview = function (moreProperties) {
var defaultProperties = CommonWeb.options.globalProperties;
var properties = $.extend(true, {}, defaultProperties, toProperties(moreProperties));
CommonWeb.Callback(CommonWeb.options.pageviewsEventName, properties);
}
CommonWeb.trackClicks = function (elements, moreProperties) {
if (typeof elements === 'undefined') {
elements = $("a");
}
$.each(elements, function (index, element) {
$(element).on('click', function (event) {
var timer = CommonWeb.options.callbackTimeout;
// combine local and global moreProperties
var properties = toClickProperties(event, element, moreProperties);
// check if the page is probably going to unload
var pageWillUnload = element.href && element.target !== '_blank' && !isMetaKey(event);
var unloadCallback = function () {
};
// if the page will unload, don't let the JS event bubble
// but navigate to the href after the click
if (pageWillUnload) {
unloadCallback = function () {
window.location.href = element.href;
};
event.preventDefault();
setTimeout(function() {
window.location.href = element.href;
}, timer);
}
CommonWeb.Callback(options.clicksEventName, properties, unloadCallback);
});
});
}
// track things that are not links; i.e. don't need any special tricks to
// prevent page unloads
CommonWeb.trackClicksPassive = function (elements, moreProperties) {
$.each(elements, function (index, element) {
$(element).on('click', function (event) {
var properties = toClickProperties(event, element, moreProperties);
CommonWeb.Callback(options.clicksEventName, properties);
});
});
}
// track form submissions
CommonWeb.trackFormSubmissions = function (elements, moreProperties) {
if (typeof elements === 'undefined') {
elements = $("form");
}
$.each(elements, function (index, element) {
var timer = CommonWeb.options.callbackTimeout;
// use to avoid duplicate submits
var callbackCalled = false;
$(element).on('submit', function (event) {
var properties = toSubmitProperties(event, element, moreProperties);
// assume true for now in this method
var pageWillUnload = true;
var unloadCallback = function () {
};
if (pageWillUnload) {
unloadCallback = function () {
// not the best approach here.
// the form can only be submitted
// once, etc.
if (!callbackCalled) {
callbackCalled = true;
element.submit();
}
};
event.preventDefault();
// We only want to fire the timeout if
// we know the page will unload. Ajax
// form submissions shouldn't submit.
setTimeout(function() {
callbackCalled = true;
element.submit();
}, timer);
}
CommonWeb.Callback(options.formSubmissionsEventName, properties, unloadCallback);
});
});
}
CommonWeb.trackInputChanges = function (elements, moreProperties) {
if (typeof elements === 'undefined') {
elements = $("input, textarea, select");
}
$.each(elements, function(index, element) {
var currentValue = $(element).val()
$(element).on('change', function(event) {
var properties = toChangeProperties(event, element, currentValue, moreProperties);
CommonWeb.Callback(options.inputChangeEventName, properties);
currentValue = $(element).val()
});
});
}
// define a namespace just for transformations of events and elements to properties
// override as a workaround to add / remove properties
CommonWeb.Transformations = {
eventToProperties: function (event) {
var properties = {};
properties['timestamp'] = event.timestamp;
properties['type'] = event.type;
properties['metaKey'] = event.metaKey;
return properties;
},
elementToProperties: function (element, extraProperties) {
var properties = extraProperties || {};
// add the tag name
properties.tagName = element.tagName;
// add the inner text for some tag types
if (element.tagName === 'A') {
properties.text = element.innerText;
}
// add each attribute
$(element.attributes).each(function (index, attr) {
properties[attr.nodeName] = attr.value;
});
// break classes out into an array if any exist
var classes = $(element).attr('class');
if (classes) {
properties['classes'] = classes.split(/\s+/)
}
properties['path'] = $(element).getPath();
return properties;
},
formElementToProperties: function (formElement) {
var formValues = {};
// TODO: remove dependency on jQuery
formValues.form_values = $(formElement).serializeArray();
// simple alias for now, but could do more as
// far as the form values are concerned
return this.elementToProperties(formElement, formValues);
},
inputElementToProperties: function(inputElement) {
var inputValues = {
value: $(inputElement).val()
};
var parentForm = $(inputElement).closest("form");
if(parentForm.size() > 0) {
inputValues.form = this.elementToProperties(parentForm[0])
}
return this.elementToProperties(inputElement, inputValues);
}
}
function toClickProperties(event, element, moreProperties) {
var defaultProperties = CommonWeb.options.globalProperties;
var properties = $.extend(true, {}, defaultProperties, toProperties(moreProperties, [event, element]));
var elementProperties = { element: CommonWeb.Transformations.elementToProperties(element, null) };
var eventProperties = { event: CommonWeb.Transformations.eventToProperties(event) };
return $.extend(true, {}, properties, elementProperties, eventProperties);
}
function toChangeProperties(event, element, previousValue, moreProperties) {
var defaultProperties = CommonWeb.options.globalProperties;
var properties = $.extend(true, {}, defaultProperties, toProperties(moreProperties, [event, element]));
var elementProperties = { element: CommonWeb.Transformations.inputElementToProperties(element) };
if(previousValue && previousValue !== "") {
elementProperties.element.previousValue = previousValue
}
var eventProperties = { event: CommonWeb.Transformations.eventToProperties(event) };
return $.extend(true, {}, properties, elementProperties, eventProperties);
}
function toSubmitProperties(event, element, moreProperties) {
var defaultProperties = CommonWeb.options.globalProperties;
var properties = $.extend(true, {}, defaultProperties, toProperties(moreProperties, [event, element]));
var elementProperties = { element: CommonWeb.Transformations.formElementToProperties(element) };
var eventProperties = { event: CommonWeb.Transformations.eventToProperties(event) };
return $.extend(true, {}, properties, elementProperties, eventProperties);
}
function toProperties(propertiesOrFunction, args) {
if (typeof propertiesOrFunction === 'function') {
return propertiesOrFunction.apply(window, args);
} else {
return propertiesOrFunction
}
}
function isMetaKey(event) {
return event.metaKey || event.altKey || event.ctrlKey || event.shiftKey;
}
/*
jQuery-GetPath v0.01, by Dave Cardwell. (2007-04-27)
http://davecardwell.co.uk/javascript/jquery/plugins/jquery-getpath/
Copyright (c)2007 Dave Cardwell. All rights reserved.
Released under the MIT License.
Usage:
var path = $('#foo').getPath();
*/
jQuery.fn.extend({
getPath: function( path ) {
// The first time this function is called, path won't be defined.
if ( typeof path == 'undefined' ) path = '';
// If this element is <html> we've reached the end of the path.
if ( this.is('html') )
return 'html' + path;
// Add the element name.
var cur = this.get(0).nodeName.toLowerCase();
// Determine the IDs and path.
var id = this.attr('id'),
klass = this.attr('class');
// Add the #id if there is one.
if ( typeof id != 'undefined' )
cur += '#' + id;
// Add any classes.
if ( typeof klass != 'undefined' )
cur += '.' + klass.split(/[\s\n]+/).join('.');
// Recurse up the DOM.
return this.parent().getPath( ' > ' + cur + path );
}
});
// backends
CommonWeb.Keen = {
Client: null,
Debug: false,
Callback: function (collection, properties, callback) {
CommonWeb.Keen.Client.addEvent(collection, properties, function() {
if (CommonWeb.Keen.Debug) {
console.log(collection + ": " + JSON.stringify(properties));
}
if (callback) {
callback();
}
});
},
globalProperties: {
keen: {
addons: [
{
"name": "keen:ip_to_geo",
"input": {
"ip": "ip_address"
},
"output": "ip_geo_info"
},
{
"name": "keen:ua_parser",
"input": {
"ua_string": "user_agent"
},
"output": "parsed_user_agent"
},
{
"name": "keen:url_parser",
"input": {
"url": "page_url"
},
"output": "parsed_page_url"
},
{
"name": "keen:referrer_parser",
"input": {
"referrer_url": "referrer_url",
"page_url": "page_url"
},
"output": "referrer_info"
}
]
},
ip_address: "${keen.ip}",
user_agent: "${keen.user_agent}"
}
};
window.CommonWeb = CommonWeb;
})();