Files
novalon-website/docs/GOOGLE_ANALYTICS_SETUP.md
T
zhangxiang f8917d4fda feat(ui): 营销站 UI/UE/UX 治理 P0→P3 收官
复评(impeccable critique)全部 Priority Issues 与 Minor Observations 落地:
- P0 数字口径:MetricsBasisNote 单一真源 + metrics-basis.test fs 防线,接入
  products/solutions/services/home/about;纯渲染端加角注,不动 DB/seed 值
- P1 转化断头路:敬请期待态 + 404 语境出口 + services 空态双出口
- P1 首页并卡:TrustSection 早鸟横幅并入 CasesSection 单张深色共创卡
- P2 CTA 治理:CONSULT_CTA_ALLOWLIST 白名单 + 逐字符扫描器,/contact CTA 全归一
- P3 polish:footer 补 服务/公司列、contact 死三元/空槽/toast、GlobalErrorTracker 幂等日志
- 文档同源:PRODUCT/CONTEXT 动效带统一 180–280ms;DESIGN.md 立 The 10px Floor;
  font-floor.test 守卫禁止再引入 <10px(保留 10/11px 有意 Bain 微标签)

Gates: type-check 0 · jest 1581/132 · lint 0e/126w · contrast 7/7 · headings 10/10
2026-09-20 11:50:58 +08:00

311 lines
6.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Google Analytics 4 集成指南
## ✅ 配置状态
**GA4 测量 ID**: `G-LGTLCR15KM`
**配置文件**: `.env.production`
```env
NEXT_PUBLIC_GA_MEASUREMENT_ID=G-LGTLCR15KM
```
## 📋 集成组件
### 1. Analytics 工具库
文件位置: `src/lib/analytics.ts`
**提供的功能:**
- `pageview(url)` - 页面浏览追踪
- `event(action, category, label?, value?)` - 事件追踪
- `trackContactForm(formData)` - 联系表单提交追踪
- `trackButtonClick(buttonName, location)` - 按钮点击追踪
- `trackPageView(pageTitle, pagePath)` - 页面视图追踪
### 2. Google Analytics 组件
文件位置: `src/components/analytics/GoogleAnalytics.tsx`
**功能:**
- 单次初始化 GA4inline snippet 内唯一一次 `gtag('config')` 负责首屏 pageview(含 consent default
- SPA 路由追踪:仅当 pathname/searchParams 变化且 URL 与上次不同时,effect 再发 `config`Google SPA 文档口径)
- 禁止在 snippet 与 effect 中重复 config(复评曾检出「GA4 初始化 2 次」,勿回退;有单测防线)
- 在所有页面启用追踪(根布局 `GoogleAnalyticsWrapper` 动态挂载,SSR 关闭)
### 3. 根布局集成
文件位置: `src/app/layout.tsx`
**已集成:**
```typescript
import { GoogleAnalytics } from "@/components/analytics/GoogleAnalytics";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<GoogleAnalytics />
{children}
</body>
</html>
);
}
```
## 🎯 使用示例
### 1. 联系表单追踪
```typescript
import { trackContactForm } from '@/lib/analytics';
function ContactForm() {
const handleSubmit = async (formData: FormData) => {
// 追踪表单提交
trackContactForm({
name: formData.get('name'),
email: formData.get('email'),
phone: formData.get('phone'),
company: formData.get('company'),
message: formData.get('message')
});
// 提交表单...
};
return <form onSubmit={handleSubmit}>...</form>;
}
```
### 2. 按钮点击追踪
```typescript
import { trackButtonClick } from '@/lib/analytics';
function CTAButton() {
const handleClick = () => {
// 追踪按钮点击
trackButtonClick('get_started', 'hero_section');
};
return <button onClick={handleClick}>开始使用</button>;
}
```
### 3. 页面浏览追踪
```typescript
import { pageview } from '@/lib/analytics';
function MyPage() {
useEffect(() => {
// 追踪页面浏览
pageview('/my-page');
}, []);
return <div>My Page</div>;
}
```
### 4. 自定义事件追踪
```typescript
import { event } from '@/lib/analytics';
function ProductCard({ product }) {
const handleAddToCart = () => {
// 追踪添加到购物车事件
event('add_to_cart', 'ecommerce', product.name, product.price);
};
return (
<div>
<h3>{product.name}</h3>
<button onClick={handleAddToCart}>添加到购物车</button>
</div>
);
}
```
## 📊 可追踪的指标
### 自动追踪
- ✅ 页面浏览(自动)
- ✅ 页面标题(自动)
- ✅ 用户会话(自动)
- ✅ 地理位置(自动)
### 手动追踪
- 📧 联系表单提交
- 🔘 按钮点击
- 📄 自定义页面视图
- 🎯 自定义事件
- 💰 交易/转化
## 🔧 配置选项
### 环境变量
```env
# 必需配置
NEXT_PUBLIC_GA_MEASUREMENT_ID=G-LGTLCR15KM
# 可选配置(在 GoogleAnalytics 组件中)
# NEXT_PUBLIC_GA_DEBUG=true # 启用调试模式
```
### 调试模式
启用调试模式查看实时数据:
```typescript
// 在 src/components/analytics/GoogleAnalytics.tsx 中
const isDebug = process.env.NEXT_PUBLIC_GA_DEBUG === 'true';
if (isDebug) {
console.log('GA Debug Mode Enabled');
}
```
## 📈 数据查看
### 访问 Google Analytics
1. 访问 https://analytics.google.com/
2. 选择你的 GA4 属性
3. 查看实时数据
4. 分析报告和趋势
### 关键报告
#### **实时报告**
- 当前在线用户
- 实时事件
- 实时页面浏览
- 地理位置
#### **受众报告**
- 用户数量
- 新用户 vs 回访用户
- 用户地理位置
- 设备和浏览器
#### **获取报告**
- 用户获取渠道
- 流量来源
- 营销活动效果
- 转化路径
#### **参与度报告**
- 平均会话时长
- 每会话页面浏览
- 跳出率
- 事件追踪
## 🧪 测试追踪
### 1. 本地测试
```bash
# 启用调试模式
NEXT_PUBLIC_GA_DEBUG=true npm run dev
```
### 2. 实时验证
1. 访问 Google Analytics 实时报告
2. 在你的网站上执行操作
3. 查看实时数据更新
### 3. 调试扩展
使用 Google Analytics Debugger 扩展:
- Chrome 扩展: Google Analytics Debugger
- Firefox 扩展: Google Analytics Debugger
## 🔒 隐私和合规
### GDPR 合规
```typescript
// 添加用户同意管理
function CookieConsent() {
const [consent, setConsent] = useState(false);
const handleAccept = () => {
setConsent(true);
// 用户同意后初始化 GA
if (consent) {
// GA 会自动初始化
}
};
return (
<div>
{!consent && (
<div className="fixed bottom-0 left-0 right-0 bg-gray-900 text-white p-4">
<p>我们使用 Google Analytics 来改进网站体验。</p>
<button onClick={handleAccept}>接受</button>
</div>
)}
</div>
);
}
```
### Cookie 设置
在 Google Analytics 中配置:
- 数据保留: 14个月
- 用户数据删除: 支持用户删除请求
- IP 匿名化: 启用
## 📞 故障排查
### 问题 1: 数据不显示
**解决方案:**
1. 检查 GA4 ID 是否正确
2. 确认环境变量已设置
3. 检查网络连接
4. 查看浏览器控制台错误
### 问题 2: 实时数据延迟
**解决方案:**
1. GA4 实时数据有 5-10 分钟延迟
2. 等待一段时间后查看
3. 检查时区设置
### 问题 3: 事件不追踪
**解决方案:**
1. 确认调用了正确的追踪函数
2. 检查事件参数是否正确
3. 启用调试模式验证
## 📚 相关资源
- [Google Analytics 4 文档](https://support.google.com/analytics/answer/9304153)
- [GA4 迁移指南](https://support.google.com/analytics/answer/10110506)
- [事件追踪最佳实践](https://support.google.com/analytics/answer/10089681)
## 🎁 示例代码
完整示例代码: `src/components/examples/ContactFormAnalyticsExample.tsx`
这个示例展示了如何在联系表单中集成 Google Analytics 追踪。
## ✅ 集成检查清单
- [x] GA4 测量 ID 配置
- [x] Analytics 工具库创建
- [x] Google Analytics 组件创建
- [x] 根布局集成
- [x] 联系表单示例创建
- [x] 文档更新
**状态**: ✅ 完全集成
Google Analytics 4 已经完全集成到项目中,现在可以追踪用户行为和访问数据了!