|
1 | 1 | "use client";
|
2 | 2 |
|
3 | 3 | import Script from "next/script";
|
| 4 | +import { usePathname, useSearchParams } from 'next/navigation'; |
4 | 5 | import { useEffect } from "react";
|
5 | 6 |
|
| 7 | +const GA_MEASUREMENT_ID = "G-ZZBSKJSFZ8"; |
| 8 | + |
6 | 9 | const GoogleAnalytics = () => {
|
| 10 | + const pathname = usePathname(); |
| 11 | + const searchParams = useSearchParams(); |
| 12 | + |
7 | 13 | useEffect(() => {
|
8 |
| - if (typeof window !== "undefined") { |
9 |
| - window.dataLayer = window.dataLayer || []; |
10 |
| - const gtag = (...args: any[]) => { |
11 |
| - window.dataLayer.push(args); |
12 |
| - }; |
13 |
| - gtag("js", new Date()); |
14 |
| - gtag("config", "G-ZZBSKJSFZ8"); |
| 14 | + if (typeof window !== "undefined" && window.gtag) { |
| 15 | + window.gtag('config', GA_MEASUREMENT_ID, { |
| 16 | + page_path: pathname + (searchParams?.toString() ? `?${searchParams.toString()}` : ''), |
| 17 | + send_page_view: true |
| 18 | + }); |
15 | 19 | }
|
16 |
| - }, []); |
| 20 | + }, [pathname, searchParams]); |
17 | 21 |
|
18 | 22 | return (
|
19 |
| - <Script |
20 |
| - async |
21 |
| - src="https://www.googletagmanager.com/gtag/js?id=G-ZZBSKJSFZ8" |
22 |
| - /> |
| 23 | + <> |
| 24 | + <Script |
| 25 | + strategy="afterInteractive" |
| 26 | + src={`https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`} |
| 27 | + /> |
| 28 | + <Script |
| 29 | + id="google-analytics" |
| 30 | + strategy="afterInteractive" |
| 31 | + > |
| 32 | + {` |
| 33 | + window.dataLayer = window.dataLayer || []; |
| 34 | + function gtag(){dataLayer.push(arguments);} |
| 35 | + gtag('js', new Date()); |
| 36 | + gtag('config', '${GA_MEASUREMENT_ID}', { |
| 37 | + page_path: window.location.pathname + window.location.search, |
| 38 | + send_page_view: true |
| 39 | + }); |
| 40 | + `} |
| 41 | + </Script> |
| 42 | + </> |
23 | 43 | );
|
24 | 44 | };
|
25 | 45 |
|
|
0 commit comments