-
Notifications
You must be signed in to change notification settings - Fork 40
/
GoogleAnalyticsInterop.ts
77 lines (60 loc) · 1.99 KB
/
GoogleAnalyticsInterop.ts
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
// declare window globals
interface Window
{
dataLayer: any[];
gtag: (...args: any[]) => void;
}
interface ObjectConstructor {
assign(...objects: Object[]): Object;
}
interface ConfigObject {
[key: string]: any
}
interface EventDataObject {
[key: string]: any
}
// declare globals
declare const dataLayer: any[];
declare const gtag: (...args: any[]) => void;
// init globals
window.dataLayer = window.dataLayer || [];
window.gtag = window.gtag || function () { dataLayer.push(arguments); };
// configure first timestamp
gtag("js", new Date());
namespace GoogleAnalyticsInterop
{
export function configure(trackingId: string, globalConfigObject: ConfigObject, debug: boolean = false): void
{
this.debug = debug;
this.globalConfigObject = globalConfigObject;
const script = document.createElement("script");
script.async = true;
script.src = "https://www.googletagmanager.com/gtag/js?id=" + trackingId;
document.head.appendChild(script);
let configObject: ConfigObject = {};
configObject.send_page_view = false;
Object.assign(configObject, globalConfigObject)
gtag("config", trackingId, configObject);
if(this.debug){
console.log(`[GTAG][${trackingId}] Configured!`);
}
}
export function navigate(trackingId: string, href: string): void
{
let configObject: ConfigObject = {};
configObject.page_location = href;
Object.assign(configObject, this.globalConfigObject)
gtag("config", trackingId, configObject);
if(this.debug){
console.log(`[GTAG][${trackingId}] Navigated: '${href}'`);
}
}
export function trackEvent(eventName: string, eventData: EventDataObject, globalEventData: EventDataObject)
{
Object.assign(eventData, globalEventData)
gtag("event", eventName, eventData);
if (this.debug) {
console.log(`[GTAG][Event triggered]: ${eventName}`);
}
}
}