-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgatsby-browser.js
More file actions
71 lines (63 loc) · 1.9 KB
/
Copy pathgatsby-browser.js
File metadata and controls
71 lines (63 loc) · 1.9 KB
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
const defaults = require("./defaults");
const isLocalLink = require("./is-local-link");
const mergeObjects = require("./merge-objects");
const getGoogleEventArgs = (options, event) => {
const { gaOptions } = options;
const isLocal = isLocalLink(event.currentTarget.href, options.localLinkMatch);
const fallbackCategory = isLocal
? gaOptions.internalLinkTitle
: gaOptions.externalLinkTitle;
return {
eventCategory: !!gaOptions.eventCategory
? gaOptions.eventCategory
: fallbackCategory,
eventAction: gaOptions.eventAction,
eventLabel: !!gaOptions.eventLabel
? gaOptions.eventLabel
: event.currentTarget.href,
};
};
const sendToGaTag = (options, event) => {
if (!window.ga) {
return;
}
const args = getGoogleEventArgs(options, event);
window.ga("send", "event", args);
};
const sendToGtag = (options, event) => {
if (!window.gtag) {
return;
}
const originalArgs = getGoogleEventArgs(options, event);
const args = {
event_category: originalArgs.eventCategory,
event_action: originalArgs.eventAction,
event_label: originalArgs.eventLabel,
};
window.gtag("event", args.event_category, args);
};
const shouldRun = (options) =>
process.env.NODE_ENV === "production" || options.runInDev;
const onClick = (event, options) => {
if (shouldRun(options)) {
sendToGaTag(options, event);
sendToGtag(options, event);
}
};
const addOnClick = (options) => {
const elements = document.getElementsByClassName(options.className);
const elemList = Array.from(elements);
for (let index = 0; index < elemList.length; index++) {
const anchorElement = elemList[index];
anchorElement.onclick = function (event) {
onClick(event, options);
};
}
};
module.exports = {
onRouteUpdate({ location, prevLocation }, pluginOptions) {
const options = mergeObjects(defaults, pluginOptions);
addOnClick(options);
return null;
},
};