-
Notifications
You must be signed in to change notification settings - Fork 149
/
index.js
312 lines (270 loc) · 8.48 KB
/
index.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
'use strict';
/**
* Module dependencies.
*/
var integration = require('@segment/analytics.js-integration');
var reject = require('reject');
/**
* GA4
*/
var GA4 = (module.exports = integration('Google Analytics 4')
.global('gtag')
.global('ga4DataLayer')
.option('measurementIds', [])
.option('cookieDomainName', 'auto')
.option('cookiePrefix', '_ga')
.option('cookieExpiration', 63072000)
.option('cookieUpdate', true)
.option('cookieFlags', '')
.option('sendAutomaticPageViewEvent', false)
.option('allowAllAdvertisingFeatures', false)
.option('allowAdvertisingPersonalization', false)
.option('disableGoogleAnalytics', false)
.option('googleReportingIdentity', 'device')
.option('userProperties', {})
/**
* Custom Events and Parameters setting. This setting is used by the track
* handler to map Segment events and fields to Google analytics events and parameters.
*
* Example:
* [
* {
* "googleEvent": "new_episode",
* "parameters": [
* {
* "key": "properties.title",
* "value": "title"
* },
* {
* "key": "properties.genre",
* "value": "genre"
* }
* ],
* "segmentEvent": "Started Episode"
* }
* ]
*/
.option('customEventsAndParameters', [])
.tag(
'<script src="//www.googletagmanager.com/gtag/js?id={{ measurementId }}&l=ga4DataLayer">'
));
/**
* Initialize.
*
* https://developers.google.com/analytics/devguides/collection/ga4
*
* @api public
*/
GA4.prototype.initialize = function() {
window.ga4DataLayer = window.ga4DataLayer || [];
window.gtag = function() {
window.ga4DataLayer.push(arguments);
};
/**
* This line is in all of the gtag examples but is not well documented. Research
* says that it is is related to deduplication.
* https://stackoverflow.com/questions/59256532/what-is-the-js-gtags-js-command
*/
window.gtag('js', new Date());
var opts = this.options;
var measurementIds = opts.measurementIds;
/**
* Avoid loading and configuring gtag.js if any are true:
* - Disable Google Analytics setting is enabled
* - No measurement IDs are configured
*/
if (!measurementIds.length || opts.disableGoogleAnalytics) {
return;
}
var config = {
/**
* Disable Google's Automatic Page View Measurement
* https://developers.google.com/analytics/devguides/collection/ga4/disable-page-view
*/
send_page_view: opts.sendAutomaticPageViewEvent,
/**
* Cookie Update
* https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id#cookie_update_parameter
*/
cookie_update: opts.cookieUpdate,
/**
* Cookie Domain Name
* https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id#cookie_domain_configuration
*/
cookie_domain: opts.cookieDomainName,
/**
* Cookie Prefix
* https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id#cookie_prefix
*/
cookie_prefix: opts.cookiePrefix,
/**
* Cookie Expiration
* https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id#cookie_expiration
*/
cookie_expires: opts.cookieExpiration,
};
var sets = [
/**
* Cookie Flags
* https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id#cookie_flags
*/
[{ cookie_flags: opts.cookieFlags }],
/**
* Disable All Advertising
* https://developers.google.com/analytics/devguides/collection/ga4/display-features#disable_all_advertising_features
*/
['allow_google_signals', opts.allowAllAdvertisingFeatures],
/**
* Disable Advertising Personalization
* https://developers.google.com/analytics/devguides/collection/ga4/display-features#disable_advertising_personalization
*/
['allow_ad_personalization_signals', opts.allowAdvertisingPersonalization]
];
// Load gtag.js using the first measurement ID, then configure using the `config` commands built above.
var self = this;
this.load({ measurementId: measurementIds[0] }, function() {
/**
* Measurement IDs.
* The same configuration information is shared across all measurement IDs.
* https://developers.google.com/analytics/devguides/collection/ga4#add_an_additional_google_analytics_property_to_an_existing_tag
*/
for (var i = 0; i < measurementIds.length; i++) {
window.gtag('config', measurementIds[i], config)
}
/**
* Set persistent values shared across all gtag.js usage.
* https://developers.google.com/gtagjs/reference/api#set
*/
for (var i = 0; i < sets.length; i++) {
// Copy the set args and append the command before calling gtag.js.
var args = sets[i].slice(0)
args.unshift('set')
window.gtag.apply(null, args);
}
self.ready();
});
};
/**
* Loaded?
*
* @api private
* @return {boolean}
*/
GA4.prototype.loaded = function() {
return !!(
window.ga4DataLayer && Array.prototype.push !== window.ga4DataLayer.push
);
};
/**
* Identify.
*
* @api public
* @param {Facade.Identify} event
*/
GA4.prototype.identify = function(identify) {
var opts = this.options;
var userPropertyMappings = opts.userProperties;
var userProperties = {};
// Map all customer-defined user property mappings.
for (var eventField in userPropertyMappings) {
if (!userPropertyMappings.hasOwnProperty(eventField)) {
continue;
}
var userProp = userPropertyMappings[eventField];
var value = identify.proxy(eventField);
userProperties[userProp] = value;
}
/**
* Map the user_id property if the Google Reporting Identity is set one of:
* - By User ID, Google signals, then device (userIdSignalsAndDevice)
* - By User ID and Devicea (userIdAndDevice)
*
* Google's Reporting Identity: https://support.google.com/analytics/answer/9213390?hl=en
*
* Note that the user ID can be appended as part of the user_properties
* object instead of being configured by an explicit command.
* https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id#set_user_id
*/
var userId = identify.userId();
var validReportingIdentity = opts.googleReportingIdentity === 'userIdSignalsAndDevice' || opts.googleReportingIdentity === 'userIdAndDevice'
if (userId && validReportingIdentity) {
userProperties.user_id = userId;
}
if (Object.keys(userProperties).length) {
window.gtag('set', 'user_properties', userProperties);
}
};
/**
* Group
*
* @api public
* @param {Facade.Group} group
*/
GA4.prototype.group = function(group) {
window.gtag('event', 'join_group', {
group_id: group.groupId()
});
};
/**
* Page
*
* @api public
* @param {Facade.Page} page
*/
GA4.prototype.page = function(page) {
// If the Send Google's Automatic Page View Measurement setting is set to true then
// don't handle page calls to avoid duplicate page_view events.
if (this.options.sendAutomaticPageViewEvent) {
return;
}
var props = page.properties();
var name = page.fullName();
var pageLocation = props.url;
var pageReferrer = page.referrer();
var pageTitle = name || props.title;
window.gtag('event', 'page_view', {
page_location: pageLocation,
page_referrer: pageReferrer,
page_title: pageTitle
});
};
/**
* Track
*
* @api public
* @param {Track} track
*/
GA4.prototype.track = function(track) {
var mappings = this.options.customEventsAndParameters;
for (var i = 0; i < mappings.length; i++) {
var mapping = mappings[i];
if (typeof mapping !== 'object') {
continue;
}
var segmentEvent = mapping.segmentEvent;
var googleEvent = mapping.googleEvent;
if (!segmentEvent || !googleEvent || segmentEvent !== track.event()) {
continue;
}
var parameterMappings = mapping.parameters || [];
var parameters = {};
if (!(parameterMappings instanceof Array)) {
continue;
}
// Map Segment event fields to Google Event Parameters.
// Text map settings that are nested in a mixed settings take on a different shape
// than a top-level text map setting.
// eg; [{ key: 'properties.genre', value: 'primary_genre }]
//
for (var j = 0; j < parameterMappings.length; j++) {
var map = parameterMappings[j] || {};
if (typeof map !== 'object' || !map.key || !map.value) {
continue;
}
var param = map.value;
var value = track.proxy(map.key);
parameters[param] = value;
}
window.gtag('event', googleEvent, parameters);
}
};