forked from ggendre/GALocalStorage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGALocalStorage.js
398 lines (339 loc) · 10.2 KB
/
GALocalStorage.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
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
/**
* Modified version of "Google Analytics for Pokki" to make it usable in PhoneGap.
* For all details and documentation:
* https://github.com/ggendre/GALocalStorage
*
* @version 1.1
* @license MIT License
* @author Guillaume Gendre, haploid.fr
*
* Original Work from Pokki team :
* Blake Machado <[email protected]>, SweetLabs, Inc.
* Fontaine Shu <[email protected]>, SweetLabs, Inc.
* see this repository : https://github.com/blakemachado/Pokki
*
* Example usage:
*
* - Place these two lines with your values in a script tag in the head of index.html
* ga_storage._setAccount('--GA-ACCOUNT-ID--');
* ga_storage._trackPageview('/index.html');
*
* - Call these whenever you want to track a page view or a custom event
* ga_storage._trackPageview('/index', 'optional title');
* ga_storage._trackEvent('category', 'action', 'label', 'value');
*/
(function () {
var IS_DEBUG = false;
var LocalStorage = function (key, initial_value) {
if (window.localStorage.getItem(key) == null && initial_value != null) {
window.localStorage.setItem(key, initial_value);
}
this._get = function () {
return window.localStorage.getItem(key);
};
this._set = function (value) {
return window.localStorage.setItem(key, value);
};
this._remove = function () {
return window.localStorage.removeItem(key);
};
this.toString = function () {
return this._get();
};
};
ga_storage = new function () {
var ga_url = 'http://www.google-analytics.com';
var ga_ssl_url = 'https://ssl.google-analytics.com';
var last_url = '/'; // used to keep track of last page view logged to pass forward to subsequent events tracked
var last_nav_url = '/'; // used to keep track of last page actually visited by the user (not popup_hidden or popup_blurred!)
var last_page_title = '-'; // used to keep track of last page view logged to pass forward to subsequent events tracked
var timer; // used for blur/focus state changes
var ga_use_ssl = false; // set by calling _enableSSL or _disableSSL
var utmac = false; // set by calling _setAccount
var utmhn = false; // set by calling _setDomain
var utmwv = '4.3'; // tracking api version
var utmcs = 'UTF-8'; // charset
var utmul = 'en-us'; // language
var utmdt = '-'; // page title
var utmt = 'event'; // analytics type
var utmhid = 0; // unique id per session
var event_map = {
hidden:{
path:'/popup_hidden',
event:'PopupHidden'
},
blurred:{
path:'/popup_blurred',
event:'PopupBlurred'
},
focused:{
path:'{last_nav_url}',
event:'PopupFocused'
}
};
var uid = new LocalStorage('ga_storage_uid');
var uid_rand = new LocalStorage('ga_storage_uid_rand');
var session_cnt = new LocalStorage('ga_storage_session_cnt');
var f_session = new LocalStorage('ga_storage_f_session');
var l_session = new LocalStorage('ga_storage_l_session');
var visitor_custom_vars = new LocalStorage('ga_storage_visitor_custom_vars');
var c_session = 0;
var custom_vars = visitor_custom_vars._get() ? JSON.parse(visitor_custom_vars._get()) : ['dummy'];
var request_cnt = 0;
function beacon_url() {
return (
ga_use_ssl ? ga_ssl_url : ga_url
) + '/__utm.gif';
}
function rand(min, max) {
return min + Math.floor(Math.random() * (max - min));
}
function get_random() {
return rand(100000000, 999999999);
}
function return_cookies(source, medium, campaign) {
source = source || '(direct)';
medium = medium || '(none)';
campaign = campaign || '(direct)';
// utma represents user, should exist for lifetime: [user_id].[random #].[first session timestamp].[last session timestamp].[start of this session timestamp].[total # of sessions]
// utmb is a session, [user_id].[requests_per_session?].[??].[start of session timestamp]
// utmc is a session, [user_id]
// utmz is a referrer cookie
var cookie = uid._get();
var ret = '__utma=' + cookie + '.' + uid_rand._get() + '.' + f_session._get() + '.' + l_session._get() + '.' + c_session + '.' + session_cnt._get() + ';';
ret += '+__utmz=' + cookie + '.' + c_session + '.1.1.utmcsr=' + source + '|utmccn=' + campaign + '|utmcmd=' + medium + ';';
ret += '+__utmc=' + cookie + ';';
ret += '+__utmb=' + cookie + '.' + request_cnt + '.10.' + c_session + ';';
return ret;
}
function generate_query_string(params) {
var qa = [];
for (var key in params) {
qa.push(key + '=' + encodeURIComponent(params[key]));
}
return '?' + qa.join('&');
}
function reset_session(c_session) {
if (IS_DEBUG) console.log('resetting session');
l_session._set(c_session);
request_cnt = 0;
utmhid = get_random();
}
function gainit() {
c_session = (new Date()).getTime();
if (IS_DEBUG) console.log('gainit', c_session);
request_cnt = 0;
utmhid = get_random();
if (uid._get() == null) {
uid._set(rand(10000000, 99999999));
uid_rand._set(rand(1000000000, 2147483647));
}
if (session_cnt._get() == null) {
session_cnt._set(1);
}
else {
session_cnt._set(parseInt(session_cnt._get()) + 1);
}
if (f_session._get() == null) {
f_session._set(c_session);
}
if (l_session._get() == null) {
l_session._set(c_session);
}
}
// public
this._enableSSL = function () {
if (IS_DEBUG) console.log("Enabling SSL");
ga_use_ssl = true;
};
// public
this._disableSSL = function () {
if (IS_DEBUG) console.log("Disabling SSL");
ga_use_ssl = false;
};
// public
this._setAccount = function (account_id) {
if (IS_DEBUG) console.log(account_id);
utmac = account_id;
gainit();
};
// public
this._setDomain = function (domain) {
if (IS_DEBUG) console.log(domain);
utmhn = domain;
};
// public
this._setLocale = function (lng, country) {
lng = (typeof lng === 'string' && lng.match(/^[a-z][a-z]$/i)) ? lng.toLowerCase() : 'en';
country = (typeof country === 'string' && country.match(/^[a-z][a-z]$/i)) ? country.toLowerCase() : 'us';
utmul = lng + '-' + country;
if (IS_DEBUG) console.log(utmul);
};
// public
this._setCustomVar = function (index, name, value, opt_scope) {
if (index < 1 || index > 5) return false;
var params = {
name:name,
value:value,
scope:opt_scope
};
custom_vars[index] = params;
// store if custom var is visitor-level (1)
if (opt_scope === 1) {
var vcv = visitor_custom_vars._get() ? JSON.parse(visitor_custom_vars._get()) : ['dummy'];
vcv[index] = params;
visitor_custom_vars._set(JSON.stringify(vcv));
}
if (IS_DEBUG) {
console.log(custom_vars);
}
return true;
};
// public
this._deleteCustomVar = function (index) {
if (index < 1 || index > 5) return false;
var scope = custom_vars[index] && custom_vars[index].scope;
custom_vars[index] = null;
if (scope === 1) {
var vcv = visitor_custom_vars._get() ? JSON.parse(visitor_custom_vars._get()) : ['dummy'];
vcv[index] = null;
visitor_custom_vars._set(JSON.stringify(vcv));
}
if (IS_DEBUG) {
console.log(custom_vars);
}
return true;
};
// public
this._trackPageview = function (path, title, source, medium, campaign) {
if (IS_DEBUG) {
console.log('Track Page View', arguments);
}
clearTimeout(timer);
request_cnt++;
if (!path) {
path = '/';
}
if (!title) {
title = utmdt;
}
// custom vars
var event = '';
if (custom_vars.length > 1) {
var names = '';
var values = '';
var scopes = '';
var last_slot = 0;
for (var i = 1; i < custom_vars.length; i++) {
if (custom_vars[i])
last_slot = i;
}
for (i = 1; i < custom_vars.length; i++) {
if (custom_vars[i]) {
var slotPrefix = '';
if (!custom_vars[i - 1])
slotPrefix = i + '!';
names += slotPrefix + custom_vars[i].name;
values += slotPrefix + custom_vars[i].value;
scopes += slotPrefix + (custom_vars[i].scope == null ? 3 : custom_vars[i].scope);
if (i < last_slot) {
names += '*';
values += '*';
scopes += '*';
}
}
}
event += '8(' + names + ')';
event += '9(' + values + ')';
event += '11(' + scopes + ')';
}
// remember page path and title for event tracking
last_url = path;
last_page_title = title;
if ([event_map.hidden.path, event_map.blurred.path].indexOf(path) < 0) {
last_nav_url = path;
}
var params = {
utmwv:utmwv,
utmn:get_random(),
utmhn:utmhn,
utmcs:utmcs,
utmul:utmul,
utmdt:title,
utmhid:utmhid,
utmp:path,
utmac:utmac,
utmcc:return_cookies(source, medium, campaign)
};
if (event != '') {
params.utme = event;
}
var url = beacon_url() + generate_query_string(params);
var img = new Image();
img.src = url;
};
// public
this._trackEvent = function (category, action, label, value, source, medium, campaign) {
if (IS_DEBUG) {
console.log('Track Event', arguments);
}
request_cnt++;
var event = '5(' + category + '*' + action;
if (label) {
event += '*' + label + ')';
}
else {
event += ')';
}
if (value) {
event += '(' + value + ')'
}
// custom vars
if (custom_vars.length > 1) {
var names = '';
var values = '';
var scopes = '';
var last_slot = 0;
for (var i = 1; i < custom_vars.length; i++) {
if (custom_vars[i])
last_slot = i;
}
for (i = 1; i < custom_vars.length; i++) {
if (custom_vars[i]) {
var slotPrefix = '';
if (!custom_vars[i - 1])
slotPrefix = i + '!';
names += slotPrefix + custom_vars[i].name;
values += slotPrefix + custom_vars[i].value;
scopes += slotPrefix + (custom_vars[i].scope == null ? 3 : custom_vars[i].scope);
if (i < last_slot) {
names += '*';
values += '*';
scopes += '*';
}
}
}
event += '8(' + names + ')';
event += '9(' + values + ')';
event += '11(' + scopes + ')';
}
var params = {
utmwv:utmwv,
utmn:get_random(),
utmhn:utmhn,
utmcs:utmcs,
utmul:utmul,
utmt:utmt,
utme:event,
utmhid:utmhid,
utmdt:last_page_title,
utmp:last_url,
utmac:utmac,
utmcc:return_cookies(source, medium, campaign)
};
var url = beacon_url() + generate_query_string(params);
var img = new Image();
img.src = url;
};
};
})();