-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle-analytics.js
194 lines (168 loc) · 4.27 KB
/
google-analytics.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
/**
* @copyright 2021-2023 Chris Zuber <[email protected]>
*/
import { loadScript } from './loader.js';
export const trustPolicies = ['goog#html'];
if (! Array.isArray(window.dataLayer)) {
window.dataLayer = [];
}
export function ga(...args) {
if (window.ga instanceof Function) {
return window.ga(...args);
}
}
export async function ready(timeout = 2000) {
await new Promise((resolve, reject) => {
if (! hasGa()) {
reject(new DOMException('Google Analytics script not loaded'));
} else {
const id = setTimeout(() => reject(new DOMException('GA ready callback timed-out')), timeout);
ga(() => {
clearTimeout(id);
resolve();
});
}
});
}
export function getUTMParams(search = window.location.search) {
const params = new URLSearchParams(search);
return {
campaign: params.get('utm_campaign'),
content: params.get('utm_content'),
medium: params.get('utm_medium'),
source: params.get('utm_source'),
term: params.get('utm_term'),
};
}
export async function create(...args) {
await ready();
return ga('create', ...args);
}
export async function remove() {
await ready();
return ga('remove');
}
export async function get(prop, timeout = 150) {
return await getTracker(timeout).then(tracker => tracker.get(prop));
}
export async function getTracker(timeout = 150) {
if (hasGa()) {
return await new Promise(async (resolve, reject) => {
const id = setTimeout(() => reject(new DOMException('Timeout obtaining tracker')), timeout);
ga(tracker => {
if (typeof tracker !== 'undefined') {
clearTimeout(id);
resolve(tracker);
} else {
reject(new DOMException('Unable to obtain GA tracker'));
}
});
});
} else {
new DOMException('Google Analytics script not loaded');
}
}
export async function set(...args) {
await ready();
return ga('set', ...args);
}
export async function require(...args) {
await ready();
return ga('require', ...args);
}
export async function provide(...args) {
await ready();
return ga('provide', ...args);
}
export async function location(url = window.location.href) {
return set('page', url);
}
export async function pageView(page = window.location.pathname) {
return send({ hitType: 'pageview', page });
}
export async function send({
eventCategory,
eventAction,
eventValue,
eventLabel,
hitType = 'event',
transport = 'beacon',
} = {}) {
await new Promise(async(hitCallback, reject) => {
if (hasGa()) {
await ready();
ga('send', { hitType, eventCategory, eventAction, eventLabel,
eventValue, transport, hitCallback });
} else {
reject(new Error('ga has not been successfully initialized'));
}
});
}
export function gtag() {
window.dataLayer.push(arguments);
}
export function hasGa() {
return window.ga instanceof Function;
}
export async function importGa(id, params = {}, { policy } = {}) {
const url = new URL('https://www.googletagmanager.com/gtag/js');
url.searchParams.set('id', id);
Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));
await loadScript(url.href, { crossOrigin: 'use-credentials', policy, }).then(() => {
gtag('js', new Date());
gtag('config', id);
create(id, 'auto');
}).catch(console.error);
return { gtag, ga, send, get, set, ready, create, remove, require,
location, pageView, getTracker, getUTMParams, hasGa };
}
export function externalHandler() {
if (hasGa()) {
send({
hitType: 'event',
eventCategory: 'outbound',
eventAction: 'click',
eventLabel: this.href,
transport: 'beacon',
});
}
}
export function telHandler() {
if (hasGa()) {
send({
hitType: 'event',
eventCategory: 'call',
eventLabel: this.href.replace('tel:', '').trim(),
transport: 'beacon',
});
}
}
export function mailtoHandler() {
if (hasGa()) {
send({
hitType: 'event',
eventCategory: 'email',
eventLabel: this.href.replace('mailto:', '').trim(),
transport: 'beacon',
});
}
}
export function geoHandler() {
if (hasGa()) {
send({
hitType: 'event',
eventCategory: 'geo',
eventLabel: this.href.replace('geo:', '').trim(),
transport: 'beacon',
});
}
}
export function genericHandler() {
if (hasGa()) {
const {
hitType = 'event', eventCategory = 'unknown', eventLabel = 'unknown',
transport = 'beacon',
} = this.dataset;
send({ hitType, eventCategory, eventLabel, transport });
}
}