fix gg tag (#6702)

This commit is contained in:
Dinh Long Nguyen 2025-10-02 00:47:38 +07:00 committed by GitHub
parent d5110de67b
commit df145d63a9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 99 additions and 51 deletions

View File

@ -20,6 +20,7 @@
content="width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover, interactive-widget=resizes-visual"
/>
<title>Jan</title>
<!-- INJECT_GOOGLE_ANALYTICS -->
</head>
<body>
<div id="root"></div>

View File

@ -2,6 +2,18 @@
* Google Analytics utility functions
*/
/**
* Track page views for SPA navigation
*/
export const pageview = (path: string) => {
if (!window.gtag) return
window.gtag('event', 'page_view', {
page_location: window.location.href,
page_path: path,
})
}
/**
* Track custom events with Google Analytics
*/
@ -9,9 +21,7 @@ export function trackEvent(
eventName: string,
parameters?: Record<string, unknown>
) {
if (!window.gtag) {
return
}
if (!window.gtag) return
window.gtag('event', eventName, parameters)
}

View File

@ -1,60 +1,21 @@
import { useEffect } from 'react'
import { useLocation } from '@tanstack/react-router'
import { pageview } from '@/lib/analytics'
export function GoogleAnalyticsProvider() {
const location = useLocation()
useEffect(() => {
// Check if GA ID is properly configured
if (!GA_MEASUREMENT_ID || GA_MEASUREMENT_ID === 'G-XXXXXXXXXX') {
console.warn(
'Google Analytics not initialized: Invalid GA_MEASUREMENT_ID'
)
return
}
// Load Google Analytics script
const script = document.createElement('script')
script.async = true
script.src = `https://www.googletagmanager.com/gtag/js?id=${GA_MEASUREMENT_ID}`
// Handle loading errors
script.onerror = () => {
console.warn('Failed to load Google Analytics script')
}
document.head.appendChild(script)
// Initialize gtag
window.dataLayer = window.dataLayer || []
window.gtag = function (...args: unknown[]) {
window.dataLayer?.push(args)
}
window.gtag('js', new Date())
window.gtag('config', GA_MEASUREMENT_ID, {
send_page_view: false, // We'll manually track page views
})
return () => {
// Cleanup: Remove script on unmount
if (script.parentNode) {
script.parentNode.removeChild(script)
}
}
}, [])
// Track page views on route change
useEffect(() => {
if (!window.gtag) {
// Skip if GA is not configured
if (!GA_MEASUREMENT_ID) {
return
}
window.gtag('event', 'page_view', {
page_path: location.pathname + location.search,
page_location: window.location.href,
page_title: document.title,
})
// Track page view with current path
const path = location.pathname + (window.location.search || '')
pageview(path)
}, [location])
return null

View File

@ -71,7 +71,9 @@ function Index() {
return (
<div className="flex h-full flex-col justify-center pb-[calc(env(safe-area-inset-bottom)+env(safe-area-inset-top))]">
<HeaderPage>
{PlatformFeatures[PlatformFeature.ASSISTANTS] && <DropdownAssistant />}
<div className="flex items-center justify-between w-full pr-2">
{PlatformFeatures[PlatformFeature.ASSISTANTS] && <DropdownAssistant />}
</div>
</HeaderPage>
<div
className={cn(

View File

@ -1,4 +1,4 @@
import { defineConfig, loadEnv } from 'vite'
import { defineConfig, loadEnv, Plugin } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import path from 'path'
@ -7,6 +7,41 @@ import { nodePolyfills } from 'vite-plugin-node-polyfills'
import packageJson from './package.json'
const host = process.env.TAURI_DEV_HOST
// Plugin to inject GA scripts in HTML
function injectGoogleAnalytics(gaMeasurementId?: string): Plugin {
return {
name: 'inject-google-analytics',
transformIndexHtml(html) {
// Only inject GA scripts if GA_MEASUREMENT_ID is set
if (!gaMeasurementId) {
// Remove placeholder if no GA ID
return html.replace(/\s*<!-- INJECT_GOOGLE_ANALYTICS -->\n?/g, '')
}
const gaScripts = `<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=${gaMeasurementId}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push(arguments); }
gtag('consent','default',{
ad_storage:'denied',
analytics_storage:'denied',
ad_user_data:'denied',
ad_personalization:'denied',
wait_for_update:500
});
gtag('js', new Date());
gtag('config', '${gaMeasurementId}', {
debug_mode: (location.hostname === 'localhost'),
send_page_view: false
});
</script>`
return html.replace('<!-- INJECT_GOOGLE_ANALYTICS -->', gaScripts)
},
}
}
// https://vite.dev/config/
export default defineConfig(({ mode }) => {
// Load env file based on `mode` in the current working directory.
@ -24,6 +59,7 @@ export default defineConfig(({ mode }) => {
nodePolyfills({
include: ['path'],
}),
injectGoogleAnalytics(env.GA_MEASUREMENT_ID),
],
resolve: {
alias: {

View File

@ -1,9 +1,46 @@
import { defineConfig } from 'vite'
import { defineConfig, Plugin } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import path from 'path'
import { TanStackRouterVite } from '@tanstack/router-plugin/vite'
// Plugin to inject GA scripts in HTML
function injectGoogleAnalytics(): Plugin {
return {
name: 'inject-google-analytics',
transformIndexHtml(html) {
const gaMeasurementId = process.env.GA_MEASUREMENT_ID
// Only inject GA scripts if GA_MEASUREMENT_ID is set
if (!gaMeasurementId) {
// Remove placeholder if no GA ID
return html.replace(/\s*<!-- INJECT_GOOGLE_ANALYTICS -->\n?/g, '')
}
const gaScripts = `<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=${gaMeasurementId}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push(arguments); }
gtag('consent','default',{
ad_storage:'denied',
analytics_storage:'denied',
ad_user_data:'denied',
ad_personalization:'denied',
wait_for_update:500
});
gtag('js', new Date());
gtag('config', '${gaMeasurementId}', {
debug_mode: (location.hostname === 'localhost'),
send_page_view: false
});
</script>`
return html.replace('<!-- INJECT_GOOGLE_ANALYTICS -->', gaScripts)
},
}
}
export default defineConfig({
plugins: [
TanStackRouterVite({
@ -13,6 +50,7 @@ export default defineConfig({
}),
react(),
tailwindcss(),
injectGoogleAnalytics(),
],
build: {
outDir: './dist-web',