Skip to content

Commit 764fd74

Browse files
committed
refactor: format GA
1 parent 480323f commit 764fd74

File tree

1 file changed

+82
-86
lines changed
  • packages/analytics-plugin-google-analytics/src

1 file changed

+82
-86
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/* global, window */
2-
let loadedInstances = {};
2+
let loadedInstances = {}
33
/* Location of gtag script */
4-
const gtagScriptSource = "https://www.googletagmanager.com/gtag/js";
4+
const gtagScriptSource = 'https://www.googletagmanager.com/gtag/js'
55
// See https://developers.google.com/analytics/devguides/collection/ga4/reference/config
66
const defaultGtagConf = {
77
// https://support.google.com/analytics/answer/7201382?hl=en#zippy=%2Cglobal-site-tag-websites
@@ -35,15 +35,15 @@ const defaultGtagConf = {
3535
* Cookie Flags
3636
* https://developers.google.com/analytics/devguides/collection/ga4/cookies-user-id#cookie_flags
3737
*/
38-
cookie_flags: "",
39-
};
38+
cookie_flags: '',
39+
}
4040

4141
const defaultConfig = {
42-
gtagName: "gtag",
43-
dataLayerName: "ga4DataLayer",
42+
gtagName: 'gtag',
43+
dataLayerName: 'ga4DataLayer',
4444
measurementIds: [],
4545
gtagConfig: defaultGtagConf,
46-
};
46+
}
4747

4848
/**
4949
* Google analytics plugin
@@ -70,72 +70,68 @@ const defaultConfig = {
7070
* })
7171
*/
7272
function googleAnalytics(pluginConfig = {}) {
73-
let pageCallCount = 0;
74-
let measurementIds = getIds(pluginConfig.measurementIds);
73+
let pageCallCount = 0
74+
let measurementIds = getIds(pluginConfig.measurementIds)
7575
const initConfig = {
7676
...defaultConfig,
7777
...pluginConfig,
78-
};
78+
}
7979

8080
return {
81-
name: "google-analytics",
81+
name: 'google-analytics',
8282
config: initConfig,
8383
// Load gtag.js and define gtag
8484
initialize: ({ config, instance }) => {
85-
const { dataLayerName, customScriptSrc, gtagName, gtagConfig, debug } =
86-
config;
85+
const { dataLayerName, customScriptSrc, gtagName, gtagConfig, debug } = config
8786
/* Inject google gtag.js script if not found */
8887
if (!scriptLoaded(customScriptSrc || gtagScriptSource)) {
89-
const customLayerName = dataLayerName ? `&l=${dataLayerName}` : "";
90-
const script = document.createElement("script");
91-
script.async = true;
92-
script.src =
93-
customScriptSrc ||
94-
`${gtagScriptSource}?id=${measurementIds[0]}${customLayerName}`;
95-
document.body.appendChild(script);
88+
const customLayerName = dataLayerName ? `&l=${dataLayerName}` : ''
89+
const script = document.createElement('script')
90+
script.async = true
91+
script.src = customScriptSrc || `${gtagScriptSource}?id=${measurementIds[0]}${customLayerName}`
92+
document.body.appendChild(script)
9693
}
9794
/* Set gtag and datalayer */
9895
if (!window[dataLayerName]) {
99-
window[dataLayerName] = window[dataLayerName] || [];
96+
window[dataLayerName] = window[dataLayerName] || []
10097
window[gtagName] = function () {
101-
window[dataLayerName].push(arguments);
102-
};
103-
window[gtagName]("js", new Date());
98+
window[dataLayerName].push(arguments)
99+
}
100+
window[gtagName]('js', new Date())
104101
}
105102
// Initialize tracker instances on page
106103
let gtagConf = {
107104
...defaultGtagConf,
108105
...(gtagConfig ? gtagConfig : {}),
109-
};
106+
}
110107
// You must explicitly delete the debug_mode parameter or all sessions will fire in debug more. Setting it false is not enough.
111108
// https://support.google.com/analytics/answer/7201382?hl=en&ref_topic=9303319#zippy=%2Cgoogle-tag-websites:~:text=To%20disable%20debug%20mode%2C%20exclude%20the%20%27debug_mode%27%20parameter%3B%20setting%20the%20parameter%20to%20false%20doesn%27t%20disable%20debug%20mode.
112109
if (debug === true) {
113-
gtagConf.debug_mode = true;
110+
gtagConf.debug_mode = true
114111
} else {
115-
delete gtagConf.debug_mode;
112+
delete gtagConf.debug_mode
116113
}
117114
/* set custom dimensions from user traits */
118-
const user = instance.user() || {};
119-
const traits = user.traits || {};
115+
const user = instance.user() || {}
116+
const traits = user.traits || {}
120117
if (Object.keys(traits).length) {
121-
window[gtagName]("set", "user_properties", traits);
118+
window[gtagName]('set', 'user_properties', traits)
122119
}
123120
/* Initialize all measurementIds */
124121
for (var i = 0; i < measurementIds.length; i++) {
125122
if (!loadedInstances[measurementIds[i]]) {
126-
console.log("a", gtagConf);
127-
window[gtagName]("config", measurementIds[i], gtagConf);
128-
loadedInstances[measurementIds[i]] = true;
123+
window[gtagName]('config', measurementIds[i], gtagConf)
124+
loadedInstances[measurementIds[i]] = true
129125
}
130126
}
131127
},
132128
// Set parameter scope at user level with 'set' method
133129
identify: ({ payload, config }) => {
134-
const { gtagName } = config;
135-
if (!window[gtagName] || !measurementIds.length) return;
130+
const { gtagName } = config
131+
if (!window[gtagName] || !measurementIds.length) return
136132
if (payload.userId) {
137133
// https://developers.google.com/analytics/devguides/collection/ga4/user-id?platform=websites#send_user_ids
138-
window[gtagName]("set", { user_id: payload.userId });
134+
window[gtagName]('set', { user_id: payload.userId })
139135
// console.log('Set userid', payload.userId)
140136
}
141137
// TODO verify this
@@ -146,17 +142,17 @@ function googleAnalytics(pluginConfig = {}) {
146142
favorite_instrument: 'double bass',
147143
season_ticketholder: 'true'
148144
}) */
149-
window[gtagName]("set", "user_properties", payload.traits);
145+
window[gtagName]('set', 'user_properties', payload.traits)
150146
// console.log('Set userprops', payload.traits)
151147
}
152148
},
153149
// Set parameter scope at page level with 'config' method
154150
page: ({ payload, config, instance }) => {
155-
const { gtagName, gtagConfig } = config;
156-
if (!window[gtagName] || !measurementIds.length) return;
157-
const { properties } = payload;
158-
const { send_to } = properties;
159-
const campaign = instance.getState("context.campaign");
151+
const { gtagName, gtagConfig } = config
152+
if (!window[gtagName] || !measurementIds.length) return
153+
const { properties } = payload
154+
const { send_to } = properties
155+
const campaign = instance.getState('context.campaign')
160156
// console.log('ga page properties', properties)
161157
/* Create pageview-related properties */
162158
const pageView = {
@@ -166,38 +162,38 @@ function googleAnalytics(pluginConfig = {}) {
166162
page_hash: properties.hash,
167163
page_search: properties.page_search,
168164
page_referrer: properties.referrer,
169-
};
170-
const campaignData = addCampaignData(campaign);
165+
}
166+
const campaignData = addCampaignData(campaign)
171167
const finalPayload = {
172168
...(send_to ? { send_to } : {}),
173169
...pageView,
174170
...campaignData,
175-
};
171+
}
176172
/* If send_page_view true, ignore first analytics.page call */
177173
if (gtagConfig && gtagConfig.send_page_view && pageCallCount === 0) {
178-
pageCallCount++;
174+
pageCallCount++
179175
// console.log('ignore first pageCallCount', pageCallCount)
180-
return;
176+
return
181177
}
182178
// console.log('Send page_view payload', finalPayload)
183-
window[gtagName]("event", "page_view", finalPayload);
179+
window[gtagName]('event', 'page_view', finalPayload)
184180
// Set after initial page view
185-
pageCallCount++;
181+
pageCallCount++
186182
},
187183
// Set parameter scope at event level with 'event' method
188184
track: ({ payload, config, instance }) => {
189-
const { properties, event } = payload;
190-
const campaign = instance.getState("context.campaign");
191-
const { gtagName } = config;
192-
if (!window[gtagName] || !measurementIds.length) return;
185+
const { properties, event } = payload
186+
const campaign = instance.getState('context.campaign')
187+
const { gtagName } = config
188+
if (!window[gtagName] || !measurementIds.length) return
193189
/* Attach campaign data */
194-
const campaignData = addCampaignData(campaign);
190+
const campaignData = addCampaignData(campaign)
195191
// Limits https://support.google.com/analytics/answer/9267744
196192
const finalPayload = {
197193
...properties,
198194
/* Attach campaign data, if exists */
199195
...campaignData,
200-
};
196+
}
201197
/*
202198
console.log('finalPayload', finalPayload)
203199
console.log('event', event)
@@ -207,64 +203,64 @@ function googleAnalytics(pluginConfig = {}) {
207203
<event_params>key: value,
208204
})
209205
*/
210-
window[gtagName]("event", event, finalPayload);
206+
window[gtagName]('event', event, finalPayload)
211207
},
212208
/* Verify gtag loaded and ready to use */
213209
loaded: () => {
214-
const { dataLayerName, customScriptSrc } = initConfig;
210+
const { dataLayerName, customScriptSrc } = initConfig
215211
const hasDataLayer =
216212
dataLayerName &&
217213
window[dataLayerName] &&
218-
Array.prototype.push === window[dataLayerName].push;
219-
return scriptLoaded(customScriptSrc || gtagScriptSource) && hasDataLayer;
214+
Array.prototype.push === window[dataLayerName].push
215+
return scriptLoaded(customScriptSrc || gtagScriptSource) && hasDataLayer
220216
},
221217
/* Custom methods */
222218
methods: {
223219
addTag(tagId, settings = {}) {
224220
// https://developers.google.com/tag-platform/devguides/install-gtagjs#add_products_to_your_tag
225221
if (window[initConfig.gtagName]) {
226-
window[initConfig.gtagName]("config", tagId, settings);
222+
window[initConfig.gtagName]('config', tagId, settings)
227223
// Add tag id
228224
if (measurementIds && !measurementIds.includes(tagId)) {
229-
measurementIds = measurementIds.concat(tagId);
225+
measurementIds = measurementIds.concat(tagId)
230226
}
231227
}
232228
},
233229
/* Disable gtag for user */
234230
disable: (ids) => {
235-
const gaIds = ids ? getIds(ids) : measurementIds;
231+
const gaIds = ids ? getIds(ids) : measurementIds
236232
for (var i = 0; i < measurementIds.length; i++) {
237-
const gaId = measurementIds[i];
233+
const gaId = measurementIds[i]
238234
if (gaIds.includes(gaId)) {
239235
// https://developers.google.com/analytics/devguides/collection/gtagjs/user-opt-out
240-
window[`ga-disable-${gaId}`] = true;
236+
window[`ga-disable-${gaId}`] = true
241237
}
242238
}
243239
},
244240
/* Enable gtag for user */
245241
enable: (ids) => {
246-
const gaIds = ids ? getIds(ids) : measurementIds;
242+
const gaIds = ids ? getIds(ids) : measurementIds
247243
for (var i = 0; i < measurementIds.length; i++) {
248-
const gaId = measurementIds[i];
244+
const gaId = measurementIds[i]
249245
if (gaIds.includes(gaId)) {
250246
// https://developers.google.com/analytics/devguides/collection/gtagjs/user-opt-out
251-
window[`ga-disable-${gaId}`] = false;
247+
window[`ga-disable-${gaId}`] = false
252248
}
253249
}
254250
},
255251
},
256-
};
252+
}
257253
}
258254

259255
function getIds(measurementIds) {
260-
if (!measurementIds) throw new Error("No GA Measurement ID defined");
256+
if (!measurementIds) throw new Error('No GA Measurement ID defined')
261257
if (Array.isArray(measurementIds)) {
262-
return measurementIds;
258+
return measurementIds
263259
}
264-
if (typeof measurementIds === "string") {
265-
return [measurementIds];
260+
if (typeof measurementIds === 'string') {
261+
return [measurementIds]
266262
}
267-
throw new Error("GA Measurement ID must be string or array of strings");
263+
throw new Error('GA Measurement ID must be string or array of strings')
268264
}
269265

270266
/**
@@ -277,23 +273,23 @@ function getIds(measurementIds) {
277273
* @param {String} [campaignData.campaignKeyword] - Keyword of campaign
278274
*/
279275
function addCampaignData(campaignData = {}) {
280-
let campaign = {};
281-
const { id, name, source, medium, content, keyword } = campaignData;
282-
if (id) campaign.campaignId = id;
283-
if (name) campaign.campaignName = name;
284-
if (source) campaign.campaignSource = source;
285-
if (medium) campaign.campaignMedium = medium;
286-
if (content) campaign.campaignContent = content;
287-
if (keyword) campaign.campaignKeyword = keyword;
288-
return campaign;
276+
let campaign = {}
277+
const { id, name, source, medium, content, keyword } = campaignData
278+
if (id) campaign.campaignId = id
279+
if (name) campaign.campaignName = name
280+
if (source) campaign.campaignSource = source
281+
if (medium) campaign.campaignMedium = medium
282+
if (content) campaign.campaignContent = content
283+
if (keyword) campaign.campaignKeyword = keyword
284+
return campaign
289285
}
290286

291287
function scriptLoaded(scriptSrc) {
292-
const scripts = document.querySelectorAll("script[src]");
293-
const regex = new RegExp(`^${scriptSrc}`);
288+
const scripts = document.querySelectorAll('script[src]')
289+
const regex = new RegExp(`^${scriptSrc}`)
294290
return Boolean(
295291
Object.values(scripts).filter((value) => regex.test(value.src)).length
296-
);
292+
)
297293
}
298294

299-
export default googleAnalytics;
295+
export default googleAnalytics

0 commit comments

Comments
 (0)