summaryrefslogtreecommitdiff
path: root/StoneIsland/plugins/cordova-plugin-google-analytics/browser/UniversalAnalyticsProxy.js
blob: a42eee393476d43c589582d756e06efe00bf5f88 (plain)
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
function UniversalAnalyticsProxy() {
  this._isDebug = false;
  this._isEcommerceRequired = false;
  this._trackingId = null;

  var namespace = window.GoogleAnalyticsObject || 'nativeGa';
  loadGoogleAnalytics.call(this, namespace);

  bindAll(this, [
    '_ensureEcommerce',
    '_uncaughtExceptionHandler',
    'addCustomDimension',
    'addTransaction',
    'addTransactionItem',
    'debugMode',
    'enableUncaughtExceptionReporting',
    'setAllowIDFACollection',
    'setAnonymizeIp',
    'setAppVersion',
    'setOptOut',
    'setUserId',
    'getVar',
    'setVar',
    'startTrackerWithId',
    'trackEvent',
    'trackException',
    'trackMetric',
    'trackTiming',
    'trackView'
  ]);
}

UniversalAnalyticsProxy.prototype = {
  startTrackerWithId: wrap(function (trackingId) {
    this._trackingId = trackingId;

    this._ga('create', {
      trackingId: trackingId,
      cookieDomain: 'auto'
    });
    this._ga('set', 'appName', document.title);
  }),

  setUserId: wrap(function (userId) {
    this._ga('set', 'userId', userId);
  }),

  setAnonymizeIp: wrap(function (anonymize) {
    this._ga('set', 'anonymizeIp', anonymize);
  }),

  setOptOut: wrap(function (optout) {
    if (!this._trackingId) {
      throw new Error('TrackingId not available');
    }
    window['ga-disable-' + this._trackingId] = optout;
  }),

  setAppVersion: wrap(function (version) {
    this._ga('set', 'appVersion', version);
  }),

  setAllowIDFACollection: wrap(function (enable) {
    // Not supported by browser platofrm
  }),

  getVar: function (param, success, error) {
    this._ga(function(tracker){
      success(tracker.get(param));
    });
  },

  setVar: wrap(function(param, value){
    this._ga('set', param, value);
  }),  

  debugMode: wrap(function () {
    this._isDebug = true;
  }),

  addCustomDimension: wrap(function (key, value) {
    this._ga('set', 'dimension' + key, value);
  }),

  trackMetric: wrap(function (key, value) {
    this._ga('set', 'metric' + key, value);
  }),

  trackEvent: send(function (category, action, label, value, newSession) {
    return {
      hitType: 'event',
      eventCategory: category,
      eventAction: action,
      eventLabel: label,
      eventValue: value
    };
  }),

  trackView: send(function (screen) {
    return {
      hitType: 'screenview',
      screenName: screen
    };
  }),

  trackException: send(function (description, fatal) {
    return {
      hitType: 'exception',
      exDescription: description,
      exFatal: fatal
    };
  }),

  trackTiming: send(function (category, intervalInMilliseconds, name, label) {
    return {
      hitType: 'timing',
      timingCategory: category,
      timingVar: name,
      timingValue: intervalInMilliseconds,
      timingLabel: label
    };
  }),

  addTransaction: wrap(function (transactionId, affiliation, revenue, tax, shipping, currencyCode) {
    this._ensureEcommerce();
    this._ga('ecommerce:addTransaction', {
      id: transactionId,
      affiliation: affiliation,
      revenue: String(revenue),
      shipping: String(shipping),
      tax: String(tax),
      currency: currencyCode
    });
  }),

  addTransactionItem: wrap(function (transactionId, name, sku, category, price, quantity, currencyCode) {
    this._ensureEcommerce();
    this._ga('ecommerce:addItem', {
      id: transactionId,
      name: name,
      sku: sku,
      category: category,
      price: String(price),
      quantity: String(quantity),
      currency: currencyCode
    });
  }),

  enableUncaughtExceptionReporting: wrap(function (enable) {
    if (enable) {
      window.addEventListener('error', this._uncaughtExceptionHandler);
    } else {
      window.removeEventListener('error', this._uncaughtExceptionHandler);
    }
  }),

  _ga: function () {
    var args = Array.prototype.slice.call(arguments);
    if (this._isDebug) {
      console.debug('UniversalAnalyticsProxy', args);
    }
    this._nativeGa.apply(this._nativeGa, args);
  },

  _uncaughtExceptionHandler: function (err) {
    this._ga('send', {
      hitType: 'exception',
      exDescription: err.message,
      exFatal: true
    });
  },

  _ensureEcommerce: function() {
    if (this._isEcommerceRequired) return;
    this._ga('require', 'ecommerce');
    this._isEcommerceRequired = true;
  }
};

function send(fn) {
  return function (success, error, args) {
    var command = fn.apply(this, args);
    var timeout = setTimeout(function () {
      error(new Error('send timeout'));
    }, 3000);

    command.hitCallback = function hitCallback(result) {
      clearTimeout(timeout);
      success(result);
    };

    try {
      this._ga('send', command);
    } catch (err) {
      clearTimeout(timeout);
      defer(error, err);
    }
  };
}

function bindAll(that, names) {
  names.forEach(function(name) {
    if (typeof that[name] === 'function') {
      that[name] = that[name].bind(that);
    }
  });
}

/**
 * Proceed to the asynchronous loading of Google's analytics.js.
 * Initialize `this._nativeGa` once the script is loaded, using
 * the `onload` callback of the `script` DOM node.
 *
 * @param {string} name Reference (global namespace) of the GA object.
 */
function loadGoogleAnalytics(name) {
  window.GoogleAnalyticsObject = name;

  window[name] = window[name] || function () {
    (window[name].q = window[name].q || []).push(arguments);
  };
  window[name].l = 1 * new Date();
  this._nativeGa = window[name];

  var script = document.createElement('script');
  var scripts = document.getElementsByTagName('script')[0];
  script.src = 'https://www.google-analytics.com/analytics.js';
  script.async = 1;
  scripts.parentNode.insertBefore(script, scripts);

  // analytics.js creates a new object once initialized, update our reference
  script.onload = (function() { this._nativeGa = window[name]; }).bind(this);
}

function wrap(fn) {
  return function (success, error, args) {
    try {
      fn.apply(this, args);
      setTimeout(success, 0);
    } catch (err) {
      defer(error, err);
    }
  };
}

function defer(fn) {
  var args = Array.prototype.slice.call(arguments, 1);
  setTimeout(function () {
    fn.apply(null, args);
  }, 0);
}

require('cordova/exec/proxy').add('UniversalAnalytics', new UniversalAnalyticsProxy());