Analytics 组件
Google Analytics 追踪组件,根据用户 Cookie 同意状态加载追踪代码。
功能概述
- 条件加载: 仅在用户接受 Cookie 后加载
- Google Analytics 4: 支持 GA4 追踪
- Script 组件: 使用 Next.js Script 组件优化加载
Props 接口
interface AnalyticsProps {
gaId: string; // Google Analytics 追踪 ID (如: G-XXXXXXXXXX)
}
Cookie 同意检查
使用 getCookieConsent 函数检查用户同意状态:
import { getCookieConsent } from "./cookie-consent";
const hasConsent = getCookieConsent() === "accepted";
GA4 初始化代码
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_ID');
依赖
next/script- Script 组件./cookie-consent- Cookie 同意工具
使用示例
import { Analytics } from "@/components/layout/analytics";
// 在 layout.tsx 中使用
<Analytics gaId="G-XXXXXXXXXX" />
加载策略
- 外部脚本:
afterInteractive- 在页面可交互后加载 - 内联脚本:
afterInteractive- 同上
注意事项
- 组件使用
"use client"指令 - 需要用户明确同意后才发送追踪数据
- 符合 GDPR 和隐私法规要求
- 追踪 ID 应从环境变量获取
隐私合规
- 尊重用户 Cookie 选择
- 用户拒绝 Cookie 时不加载追踪代码
- 建议配合 Cookie 同意横幅使用