/
browser.js
365 lines (329 loc) · 12.6 KB
/
browser.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
/* global ga */
const defaultConfig = {
/* See description below */
trackingId: null,
/* See description below */
debug: false,
/* See description below */
anonymizeIp: false,
/* See description below */
customDimensions: {},
/* See description below */
resetCustomDimensionsOnPage: [],
/* See description below */
setCustomDimensionsToPage: true,
/* Custom metrics https://bit.ly/3c5de88 */
// TODO customMetrics: { key: 'metric1' }
/* Content groupings https://bit.ly/39Zt3Me */
// TODO contentGroupings: { key: 'contentGroup1' }
}
let loadedInstances = {}
/**
* Google analytics plugin
* @link https://getanalytics.io/plugins/google-analytics/
* @link https://analytics.google.com/analytics/web/
* @link https://developers.google.com/analytics/devguides/collection/analyticsjs
* @param {object} pluginConfig - Plugin settings
* @param {string} pluginConfig.trackingId - Google Analytics site tracking Id
* @param {boolean} [pluginConfig.debug] - Enable Google Analytics debug mode
* @param {boolean} [pluginConfig.anonymizeIp] - Enable [Anonymizing IP addresses](https://bit.ly/3c660Rd) sent to Google Analytics. [See details below](#anonymize-visitor-ips)
* @param {object} [pluginConfig.customDimensions] - Map [Custom dimensions](https://bit.ly/3c5de88) to send extra information to Google Analytics. [See details below](#using-ga-custom-dimensions)
* @param {object} [pluginConfig.resetCustomDimensionsOnPage] - Reset custom dimensions by key on analytics.page() calls. Useful for single page apps.
* @param {boolean} [pluginConfig.setCustomDimensionsToPage] - Mapped dimensions will be set to the page & sent as properties of all subsequent events on that page. If false, analytics will only pass custom dimensions as part of individual events
* @param {string} [pluginConfig.instanceName] - Custom tracker name for google analytics. Use this if you need multiple googleAnalytics scripts loaded
* @param {string} [pluginConfig.customScriptSrc] - Custom URL for google analytics script, if proxying calls
* @return {*}
* @example
*
* googleAnalytics({
* trackingId: 'UA-1234567'
* })
*/
function googleAnalytics(pluginConfig = {}) {
let pageCalledOnce = false
// Allow for multiple google analytics instances
const { instanceName, instancePrefix } = getInstanceDetails(pluginConfig)
return {
name: 'google-analytics',
config: {
...defaultConfig,
...pluginConfig
},
// Load google analytics
initialize: (pluginApi) => {
const { config, instance } = pluginApi
if (!config.trackingId) throw new Error('No GA trackingId defined')
// var to hoist
const scriptSrc = config.customScriptSrc || 'https://www.google-analytics.com/analytics.js'
// Load google analytics script to page
if (gaNotLoaded(scriptSrc)) {
/* eslint-disable */
(function(i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function() {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', scriptSrc, 'ga')
/* eslint-enable */
}
// Initialize tracker instance on page
if (!loadedInstances[instanceName]) {
const gaConfig = {
cookieDomain: config.domain || 'auto',
siteSpeedSampleRate: config.siteSpeedSampleRate || 1,
sampleRate: config.sampleRate || 100,
allowLinker: true,
// useAmpClientId: config.useAmpClientId
}
if (instanceName) {
gaConfig.name = instanceName
}
ga('create', config.trackingId, gaConfig)
if (config.debug) {
// Disable sends to GA http://bit.ly/2Ro0vTR
ga(`${instancePrefix}set`, 'sendHitTask', null)
window.ga_debug = { trace: true }
}
if (config.anonymizeIp) {
ga(`${instancePrefix}set`, 'anonymizeIp', true)
}
/* set custom dimenions from user traits */
const user = instance.user() || {}
const traits = user.traits || {}
if (Object.keys(traits).length) {
const customDimensions = formatObjectIntoDimensions(traits, config)
ga(`${instancePrefix}set`, customDimensions)
}
loadedInstances[instanceName] = true
}
},
// Google Analytics page view
page: ({ payload, config, instance }) => {
const { properties } = payload
const { resetCustomDimensionsOnPage, customDimensions } = config
const campaign = instance.getState('context.campaign')
if (gaNotLoaded()) return
/* If dimensions are specifiied to reset, clear them before page view */
if (resetCustomDimensionsOnPage && resetCustomDimensionsOnPage.length) {
const resetDimensions = resetCustomDimensionsOnPage.reduce((acc, key) => {
if (customDimensions[key]) {
acc[customDimensions[key]] = null // { dimension1: null } etc
}
return acc
}, {})
if (Object.keys(resetDimensions).length) {
// Reset custom dimenions
ga(`${instancePrefix}set`, resetDimensions)
}
}
const path = properties.path || document.location.pathname
const pageView = {
page: path,
title: properties.title,
location: properties.url
}
let pageData = {
page: path,
title: properties.title
}
// allow referrer override if referrer was manually set
if (properties.referrer !== document.referrer) {
pageData.referrer = properties.referrer
}
const campaignData = addCampaignData(campaign)
const dimensions = setCustomDimenions(properties, config, instancePrefix)
/* Dimensions will only be included in the event if config.setCustomDimensionsToPage is false */
const finalPayload = {
...pageView,
...campaignData,
...dimensions
}
ga(`${instancePrefix}set`, pageData)
// Remove location for SPA tracking after initial page view
if (pageCalledOnce) {
delete finalPayload.location
}
/* send page view to GA */
ga(`${instancePrefix}send`, 'pageview', finalPayload)
// Set after initial page view
pageCalledOnce = true
},
/**
* Google Analytics track event
* @example
*
* analytics.track('playedVideo', {
* category: 'Videos',
* label: 'Fall Campaign',
* value: 42
* })
*/
track: ({ payload, config, instance }) => {
const { properties, event } = payload
const { label, value, category, nonInteraction } = properties
const campaign = instance.getState('context.campaign')
// TODO inline this trackEvent
trackEvent({
hitType: 'event',
event: event,
label: label,
category: category || 'All',
value: value,
nonInteraction,
campaign: campaign
}, config, payload)
},
identify: ({ payload, config }) => {
identifyVisitor(payload.userId, payload.traits, config)
},
loaded: () => {
return !!window.gaplugins
}
}
}
export default googleAnalytics
function gaNotLoaded(scriptSrc) {
if (scriptSrc) {
return !scriptLoaded(scriptSrc)
}
return typeof ga === 'undefined'
}
function getInstanceDetails(pluginConfig) {
const { instanceName } = pluginConfig
return {
instancePrefix: (instanceName) ? `${instanceName}.` : '',
instanceName: instanceName
}
}
/**
* Send event tracking to Google Analytics
* @param {object} eventData - GA event payload
* @param {string} [eventData.hitType = 'event'] - hitType https://bit.ly/2Jab9L1 one of 'pageview', 'screenview', 'event', 'transaction', 'item', 'social', 'exception', 'timing'
* @param {string} [eventData.event] - event Action https://bit.ly/2CUzeoz
* @param {string} [eventData.label] - event Label http://bit.ly/2oo8eb3
* @param {string} [eventData.category] - event Category http://bit.ly/2EAy9UP
* @param {string} [eventData.nonInteraction = false] - nonInteraction https://bit.ly/2CUzeoz
* @return {object} sent data
*/
export function trackEvent(eventData, opts = {}, payload) {
if (gaNotLoaded()) return
const { instancePrefix } = getInstanceDetails(opts)
const data = {
// hitType https://bit.ly/2Jab9L1 one of 'pageview', 'screenview', 'event', 'transaction', 'item', 'social', 'exception', 'timing'
hitType: eventData.hitType || 'event',
// eventAction https://bit.ly/2CUzeoz
eventAction: eventData.event,
// eventLabel http://bit.ly/2oo8eb3
eventLabel: eventData.label,
// eventCategory http://bit.ly/2EAy9UP
eventCategory: eventData.category || 'All',
// nonInteraction https://bit.ly/2CUzeoz
nonInteraction: (eventData.nonInteraction !== undefined) ? !!eventData.nonInteraction : false
}
if (eventData.value) {
// how much is this action worth?
data.eventValue = format(eventData.value)
}
/* Attach campaign data */
const campaignData = addCampaignData(eventData)
/* Set Dimensions or return them for payload is config.setCustomDimensionsToPage is false */
const dimensions = setCustomDimenions(payload.properties, opts, instancePrefix)
const finalPayload = {
...data,
/* Attach campaign data, if exists */
...campaignData,
/* Dimensions will only be included in the event if config.setCustomDimensionsToPage is false */
...dimensions
}
/* Send data to Google Analytics */
ga(`${instancePrefix}send`, 'event', finalPayload)
return finalPayload
}
/**
* Add campaign data to GA payload https://bit.ly/34qFCPn
* @param {Object} [campaignData={}] [description]
* @param {String} [campaignData.campaignName] - Name of campaign
* @param {String} [campaignData.campaignSource] - Source of campaign
* @param {String} [campaignData.campaignMedium] - Medium of campaign
* @param {String} [campaignData.campaignContent] - Content of campaign
* @param {String} [campaignData.campaignKeyword] - Keyword of campaign
*/
function addCampaignData(campaignData = {}) {
let campaign = {}
const { name, source, medium, content, keyword } = campaignData
if (name) campaign.campaignName = name
if (source) campaign.campaignSource = source
if (medium) campaign.campaignMedium = medium
if (content) campaign.campaignContent = content
if (keyword) campaign.campaignKeyword = keyword
return campaign
}
/* Todo add includeSearch options ¯\_(ツ)_/¯
function getPagePath(props, opts = {}) {
if (!props) return
if (opts.includeSearch && props.search) {
return `${props.path}${props.search}`
}
return props.path
}
*/
// properties, data=opts
function formatObjectIntoDimensions(properties, opts = {}) {
const { customDimensions } = opts
// TODO map opts.customMetrics; Object.keys(customMetrics) { key: 'metric1' }
// TODO map opts.contentGroupings; Object.keys(contentGroupings) { key: 'contentGroup1' }
/* Map values from payload to any defined custom dimensions */
return Object.keys(customDimensions).reduce((acc, key) => {
const dimensionKey = customDimensions[key]
var value = get(properties, key) || properties[key]
if (typeof value === 'boolean') {
value = value.toString()
}
if (value || value === 0) {
acc[dimensionKey] = value
return acc
}
return acc
}, {})
}
function get(obj, key, def, p, undef) {
key = key.split ? key.split('.') : key
for (p = 0; p < key.length; p++) {
obj = obj ? obj[key[p]] : undef
}
return obj === undef ? def : obj
}
function setCustomDimenions(props = {}, opts, instancePrefix) {
const customDimensions = formatObjectIntoDimensions(props, opts)
if (!Object.keys(customDimensions).length) {
return {}
}
// If setCustomDimensionsToPage false, don't save custom dimenions from event to page
if (!opts.setCustomDimensionsToPage) {
return customDimensions
}
// Set custom dimensions
ga(`${instancePrefix}set`, customDimensions)
return {}
}
/**
* Identify a visitor by Id
* @param {string} id - unique visitor ID
*/
export function identifyVisitor(id, traits = {}, conf = {}) {
if (gaNotLoaded()) return
const { instancePrefix } = getInstanceDetails(conf)
if (id) ga(`${instancePrefix}set`, 'userId', id)
if (Object.keys(traits).length) {
const custom = formatObjectIntoDimensions(traits, conf)
ga(`${instancePrefix}set`, custom)
}
}
function scriptLoaded(scriptSrc) {
const scripts = document.querySelectorAll('script[src]')
return !!Object.keys(scripts).filter((key) => (scripts[key].src || '') === scriptSrc).length
}
function format(value) {
if (!value || value < 0) return 0
return Math.round(value)
}