diff --git a/src/main.tsx b/src/main.tsx index e6772e1..ca223cf 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -32,12 +32,12 @@ const initializeGA4 = () => { script.onload = () => { (window as any).dataLayer = (window as any).dataLayer || []; - function gtag(...args: any[]) { + (window as any).gtag = function (...args: any[]) { (window as any).dataLayer.push(args); - } - gtag("js", new Date()); + }; - gtag("config", ga4Id); + (window as any).gtag("js", new Date()); + (window as any).gtag("config", ga4Id); }; }; diff --git a/src/types/global.d.ts b/src/types/global.d.ts index 78d6e2d..e32991d 100644 --- a/src/types/global.d.ts +++ b/src/types/global.d.ts @@ -28,7 +28,7 @@ declare global { } interface Window { // eslint-disable-next-line @typescript-eslint/no-explicit-any - gtag: (...args: any[]) => void; + gtag: (event: string, action: string, params?: Record) => void; response?: { receiveScanResult: (jsonData: string) => void; receiveGeneratedReview: (jsonData: string) => void; diff --git a/src/utils/gtag.ts b/src/utils/gtag.ts index 7e8d7ed..d7cfa54 100644 --- a/src/utils/gtag.ts +++ b/src/utils/gtag.ts @@ -1,6 +1,10 @@ export const gTagLogEvent = (eventLabel: string) => { - window.gtag("event", "click", { - event_category: "button", - event_label: eventLabel, - }); + if (typeof window !== "undefined" && typeof window.gtag === "function") { + window.gtag("event", "click", { + event_category: "button", + event_label: eventLabel, + }); + } else { + console.warn("Google Analytics is not initialized yet."); + } };