From 24bbd635d0c6141d6c86365fce507d927ebbfb70 Mon Sep 17 00:00:00 2001 From: JB Hutch Date: Thu, 26 Oct 2023 15:46:05 -0400 Subject: [PATCH] Add support for trackEvent --- src/index.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/src/index.ts b/src/index.ts index 97e5766..8da2072 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,6 +3,7 @@ interface Fathom { enableTrackingForMe: () => void; trackPageview: (opts?: PageViewOptions) => void; trackGoal: (code: string, cents: number) => void; + trackEvent: (code: string, opts?: EventOptions) => void; setSite: (id: string) => void; } @@ -11,6 +12,11 @@ export type PageViewOptions = { referrer?: string; }; +export type EventOptions = { + _value?: number, + _site_id?: string +} + // refer to https://usefathom.com/support/tracking-advanced export type LoadOptions = { url?: string; @@ -25,6 +31,7 @@ export type LoadOptions = { type FathomCommand = | { type: 'trackPageview'; opts: PageViewOptions | undefined } | { type: 'trackGoal'; code: string; cents: number } + | { type: 'trackEvent'; event_name: string; opts: EventOptions | undefined } | { type: 'blockTrackingForMe' } | { type: 'enableTrackingForMe' } | { type: 'setSite'; id: string }; @@ -61,6 +68,10 @@ const flushQueue = (): void => { trackGoal(command.code, command.cents); return; + case 'trackEvent': + trackEvent(command.event_name, command.opts); + return; + case 'enableTrackingForMe': enableTrackingForMe(); return; @@ -155,6 +166,8 @@ export const trackPageview = (opts?: PageViewOptions): void => { * * @param code - The goal ID. * @param cents - The value in cents. + * @deprecated If you are using this to track an existing goal, however, it will continue to work. + * @see https://usefathom.com/docs/features/events */ export const trackGoal = (code: string, cents: number) => { if (window.fathom) { @@ -164,6 +177,22 @@ export const trackGoal = (code: string, cents: number) => { } }; +/** + * Tracks a dynamic event. + * + * @param event_name - This can be nearly anything you want. Avoid special chars and emojis + * @param _value - The value in cents. + * @param _site_id - The value in cents. + * @see https://usefathom.com/docs/features/events + */ +export const trackEvent = (event_name: string, opts?: EventOptions) => { + if (window.fathom) { + window.fathom.trackEvent(event_name, opts); + } else { + enqueue({ type: 'trackEvent', event_name, opts }); + } +}; + /** * Blocks tracking for the current visitor. *