From f632678f688af4ac15c0c504dd8041dfcf5e41a9 Mon Sep 17 00:00:00 2001 From: Stephen Chiang Date: Fri, 29 Apr 2022 20:53:09 +0200 Subject: [PATCH] Add GA4 utils --- app/__utils__/gtags.client.ts | 48 +++++++++++++++++++++++++++++++++++ app/__utils__/index.ts | 1 + 2 files changed, 49 insertions(+) create mode 100644 app/__utils__/gtags.client.ts create mode 100644 app/__utils__/index.ts diff --git a/app/__utils__/gtags.client.ts b/app/__utils__/gtags.client.ts new file mode 100644 index 00000000..2fdc6900 --- /dev/null +++ b/app/__utils__/gtags.client.ts @@ -0,0 +1,48 @@ +declare global { + interface Window { + gtag: ( + option: string, + gaTrackingId: string, + options: Record + ) => void; + } +} + +/** + * @example + * https://developers.google.com/analytics/devguides/collection/gtagjs/pages + */ +export const pageview = (url: string, trackingId: string) => { + if (!window.gtag) { + console.warn( + "window.gtag is not defined. This could mean your google anylatics script has not loaded on the page yet." + ); + return; + } + window.gtag("config", trackingId, { + page_path: url, + }); +}; + +/** + * @example + * https://developers.google.com/analytics/devguides/collection/gtagjs/events + */ +export const event = ({ + action, + category, + label, + value, +}: Record) => { + if (!window.gtag) { + console.warn( + "window.gtag is not defined. This could mean your google anylatics script has not loaded on the page yet." + ); + return; + } + window.gtag("event", action, { + event_category: category, + event_label: label, + value: value, + }); +}; diff --git a/app/__utils__/index.ts b/app/__utils__/index.ts new file mode 100644 index 00000000..c9839e5d --- /dev/null +++ b/app/__utils__/index.ts @@ -0,0 +1 @@ +export * as gtag from "./gtags.client";