-
Notifications
You must be signed in to change notification settings - Fork 302
Expand file tree
/
Copy pathanalytics.ts
More file actions
78 lines (74 loc) · 1.96 KB
/
Copy pathanalytics.ts
File metadata and controls
78 lines (74 loc) · 1.96 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
72
73
74
75
76
77
78
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*/
const createFunctionWithTimeout = (
callback: () => void,
opt_timeout = 1000
) => {
let called = false;
const raceCallback = () => {
if (!called) {
called = true;
callback();
}
};
setTimeout(raceCallback, opt_timeout);
return raceCallback;
};
interface CustomEvent {
/** The value that will appear as the event action in Google Analytics Event reports. */
action: string;
/** The category of the event. */
category?: string;
/** The label of the event. */
label?: string;
/** A non-negative integer that will appear as the event value. */
value: number;
/**
* Whether the even is non-interactive
* @see https://support.google.com/analytics/answer/1033068#NonInteractionEvents
* @default false
*/
nonInteraction?: boolean;
/**
* A function that gets called as soon as an event has been successfully sent.
* @see https://developers.google.com/analytics/devguides/collection/gtagjs/sending-data
*/
hitCallback?: () => void;
/**
* Max ms timeout for callback
* @default 1000
*/
callbackTimeout?: number;
}
/**
* This allows the user to create custom events within their Next projects.
*
* @see https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#events
*/
export function trackCustomEvent({
category,
action,
label,
value,
nonInteraction = false,
hitCallback,
callbackTimeout = 1000,
}: CustomEvent) {
if (typeof window !== `undefined` && (window as any).gtag) {
const trackingEventOptions: any = {
event_category: category,
event_action: action,
event_label: label,
value,
non_interaction: nonInteraction,
};
if (hitCallback && typeof hitCallback === `function`) {
trackingEventOptions.event_callback = createFunctionWithTimeout(
hitCallback,
callbackTimeout
);
}
(window as any).gtag(`event`, trackingEventOptions);
}
}