From f3bbd6c70bf60ee7bbdfdb354747721ec257de71 Mon Sep 17 00:00:00 2001 From: Sarah Gerrard <98355961+LadyBluenotes@users.noreply.github.com> Date: Mon, 30 Mar 2026 09:48:53 -0700 Subject: [PATCH] fix: restore GA4 pageview tracking for client-side navigation --- src/routes/__root.tsx | 53 +++++++++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index 9c19d09c..959ed34b 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -261,46 +261,55 @@ function SearchHotkeyController() { } function IdleGtmLoader() { + const pagePath = useRouterState({ + select: (s) => { + const pathname = s.resolvedLocation?.pathname || '/' + const search = s.resolvedLocation?.searchStr || '' + + return `${pathname}${search}` + }, + }) + React.useEffect(() => { const gaId = 'G-JMT1Z50SPS' const existingScript = document.querySelector( `script[src*="googletagmanager.com/gtag/js?id=${gaId}"]`, ) - if (existingScript) return - - const inject = () => { - if (!window.dataLayer) { - window.dataLayer = [] - } + if (!window.dataLayer) { + window.dataLayer = [] + } - if (!window.gtag) { - window.gtag = (...args: unknown[]) => { - window.dataLayer?.push(args) - } + if (!window.gtag) { + window.gtag = (...args: unknown[]) => { + window.dataLayer?.push(args) } + } - window.gtag('js', new Date()) - window.gtag('config', gaId) + window.gtag('js', new Date()) + window.gtag('config', gaId, { + send_page_view: false, + }) + if (!existingScript) { const script = document.createElement('script') script.async = true script.src = `https://www.googletagmanager.com/gtag/js?id=${gaId}` document.head.appendChild(script) } + }, []) - if ('requestIdleCallback' in window) { - const idleHandle = window.requestIdleCallback(inject, { timeout: 2500 }) - return () => { - window.cancelIdleCallback(idleHandle) - } + React.useEffect(() => { + if (!window.gtag) { + return } - const timeoutHandle = globalThis.setTimeout(inject, 2500) - return () => { - globalThis.clearTimeout(timeoutHandle) - } - }, []) + window.gtag('event', 'page_view', { + page_title: document.title, + page_path: pagePath, + page_location: window.location.href, + }) + }, [pagePath]) return null }