85 lines
2.2 KiB
TypeScript
85 lines
2.2 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect } from "react";
|
|
import Script from "next/script";
|
|
import { usePathname, useSearchParams } from "next/navigation";
|
|
|
|
declare global {
|
|
interface Window {
|
|
dataLayer?: unknown[];
|
|
gtag?: (...args: unknown[]) => void;
|
|
}
|
|
}
|
|
|
|
function trackPageView(url: string, gaMeasurementId?: string) {
|
|
if (!gaMeasurementId || !window.gtag) {
|
|
return;
|
|
}
|
|
|
|
window.gtag("event", "page_view", {
|
|
page_location: window.location.href,
|
|
page_path: url,
|
|
page_title: document.title,
|
|
});
|
|
}
|
|
|
|
type AnalyticsProps = {
|
|
clarityProjectId?: string;
|
|
gaMeasurementId?: string;
|
|
};
|
|
|
|
export default function Analytics({ clarityProjectId, gaMeasurementId }: AnalyticsProps) {
|
|
const pathname = usePathname();
|
|
const searchParams = useSearchParams();
|
|
|
|
useEffect(() => {
|
|
if (!pathname) {
|
|
return;
|
|
}
|
|
|
|
const query = searchParams.toString();
|
|
const url = query ? `${pathname}?${query}` : pathname;
|
|
trackPageView(url, gaMeasurementId);
|
|
}, [gaMeasurementId, pathname, searchParams]);
|
|
|
|
if (!gaMeasurementId && !clarityProjectId) {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<>
|
|
{gaMeasurementId ? (
|
|
<>
|
|
<Script
|
|
src={`https://www.googletagmanager.com/gtag/js?id=${gaMeasurementId}`}
|
|
strategy="afterInteractive"
|
|
/>
|
|
<Script id="ga4-init" strategy="afterInteractive">
|
|
{`
|
|
window.dataLayer = window.dataLayer || [];
|
|
function gtag(){dataLayer.push(arguments);}
|
|
window.gtag = gtag;
|
|
gtag('js', new Date());
|
|
gtag('config', '${gaMeasurementId}', { send_page_view: false });
|
|
`}
|
|
</Script>
|
|
</>
|
|
) : null}
|
|
{clarityProjectId ? (
|
|
<Script id="clarity-init" strategy="afterInteractive">
|
|
{`
|
|
(function(c,l,a,r,i,t,y){
|
|
c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
|
|
t=l.createElement(r);
|
|
t.async=1;
|
|
t.src="https://www.clarity.ms/tag/" + i;
|
|
y=l.getElementsByTagName(r)[0];
|
|
y.parentNode.insertBefore(t,y);
|
|
})(window, document, "clarity", "script", "${clarityProjectId}");
|
|
`}
|
|
</Script>
|
|
) : null}
|
|
</>
|
|
);
|
|
}
|