forked from snowplow/snowplow-javascript-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
61 lines (56 loc) · 1.85 KB
/
Copy pathindex.ts
File metadata and controls
61 lines (56 loc) · 1.85 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
import { BrowserPlugin, BrowserTracker, dispatchToTrackersInCollection } from '@snowplow/browser-tracker-core';
import { buildSelfDescribingEvent, DynamicContext, resolveDynamicContext } from '@snowplow/tracker-core';
import { WEB_VITALS_SCHEMA } from './schemata';
import { attachWebVitalsPageListeners, webVitalsListener } from './utils';
const _trackers: Record<string, BrowserTracker> = {};
let listenersAttached = false;
interface WebVitalsPluginOptions {
loadWebVitalsScript?: boolean;
webVitalsSource?: string;
context?: DynamicContext;
}
const defaultPluginOptions = {
context: [],
};
/**
* Adds Web Vitals measurement events
*
* @remarks
*/
export function WebVitalsPlugin(pluginOptions: WebVitalsPluginOptions = defaultPluginOptions): BrowserPlugin {
const webVitalsObject: Record<string, unknown> = {};
const options = { ...defaultPluginOptions, ...pluginOptions };
let trackerId: string;
return {
activateBrowserPlugin: (tracker) => {
trackerId = tracker.id;
_trackers[trackerId] = tracker;
function sendWebVitals() {
if (!Object.keys(webVitalsObject).length) {
return;
}
dispatchToTrackersInCollection(Object.keys(_trackers), _trackers, (t) => {
t.core.track(
buildSelfDescribingEvent({
event: {
schema: WEB_VITALS_SCHEMA,
data: webVitalsObject,
},
}),
resolveDynamicContext(options.context ?? [], webVitalsObject)
);
});
}
/*
* Attach page listeners only once per page.
* Prevent multiple trackers from attaching listeners multiple times.
*/
if (!listenersAttached) {
webVitalsListener(webVitalsObject);
attachWebVitalsPageListeners(sendWebVitals);
listenersAttached = true;
}
return;
},
};
}