feat:调整google analysis加载条件

This commit is contained in:
hzm
2026-02-05 12:20:18 +08:00
parent 1a2562e198
commit ce0370fee1
2 changed files with 31 additions and 13 deletions

View File

@@ -0,0 +1,29 @@
'use client';
import { useLayoutEffect, useState } from 'react';
import Script from 'next/script';
export default function AnalyticsGate({ GA_ID }) {
const [enabled, setEnabled] = useState(false);
useLayoutEffect(() => {
try {
const href = window.location.href || '';
setEnabled(href.includes('hzm0321'));
} catch {}
}, []);
if (!enabled) return null;
return (
<>
<Script src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`} strategy="afterInteractive" />
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_ID}');
`}
</Script>
</>
);
}

View File

@@ -1,5 +1,6 @@
import Script from 'next/script';
import './globals.css';
import AnalyticsGate from './components/AnalyticsGate';
export const metadata = {
title: '基估宝',
@@ -13,21 +14,9 @@ export default function RootLayout({ children }) {
<html lang="zh-CN">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
{/* Google Analytics */}
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`}
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_ID}');
`}
</Script>
</head>
<body>
<AnalyticsGate GA_ID={GA_ID} />
{children}
</body>
</html>