|
1 | | -"use client"; |
2 | | - |
3 | | -import { useEffect, useRef, useState } from "react"; |
4 | | -import { usePathname } from "next/navigation"; |
5 | 1 | import Script from "next/script"; |
6 | 2 |
|
7 | 3 | const measurementId = process.env.NEXT_PUBLIC_GA_ID || "G-VWDH18RX25"; |
8 | 4 |
|
9 | | -declare global { |
10 | | - interface Window { |
11 | | - dataLayer: unknown[][]; |
12 | | - gtag: (...args: unknown[]) => void; |
13 | | - } |
14 | | -} |
15 | | - |
16 | 5 | export default function GoogleAnalytics() { |
17 | | - const pathname = usePathname(); |
18 | | - const lastTrackedPath = useRef<string | null>(null); |
19 | | - const hasTrackedInitialPage = useRef(false); |
20 | | - const pendingPageViews = useRef<Array<{ pathname: string; pageTitle: string }>>([]); |
21 | | - const [gtagReady, setGtagReady] = useState(false); |
22 | | - |
23 | | - useEffect(() => { |
24 | | - if (!pathname) return; |
25 | | - |
26 | | - if (!hasTrackedInitialPage.current) { |
27 | | - hasTrackedInitialPage.current = true; |
28 | | - lastTrackedPath.current = pathname; |
29 | | - return; |
30 | | - } |
31 | | - |
32 | | - if (lastTrackedPath.current !== pathname) { |
33 | | - lastTrackedPath.current = pathname; |
34 | | - pendingPageViews.current.push({ pathname, pageTitle: document.title }); |
35 | | - } |
36 | | - |
37 | | - if (!gtagReady || typeof window.gtag !== "function") return; |
38 | | - |
39 | | - for (const pageView of pendingPageViews.current) { |
40 | | - window.gtag("event", "page_view", { |
41 | | - page_path: pageView.pathname, |
42 | | - page_location: `${window.location.origin}${pageView.pathname}`, |
43 | | - page_title: pageView.pageTitle, |
44 | | - }); |
45 | | - } |
46 | | - pendingPageViews.current = []; |
47 | | - }, [gtagReady, pathname]); |
48 | | - |
49 | 6 | return ( |
50 | 7 | <> |
51 | 8 | <Script |
52 | 9 | src={`https://www.googletagmanager.com/gtag/js?id=${measurementId}`} |
53 | 10 | strategy="afterInteractive" |
54 | | - onReady={() => setGtagReady(true)} |
55 | 11 | /> |
56 | 12 | <Script id="google-analytics-init" strategy="beforeInteractive"> |
57 | 13 | {`window.dataLayer = window.dataLayer || []; |
|
0 commit comments