fix(analytics): 分析 Cookie 改 opt-in,后台不加载 GA(DEF-09)

两处独立问题:

① 默认同意。`DEFAULT_PREFERENCES.analytics` 是 true,且 GA inline snippet 的
   `consent default` 直接写 `analytics_storage: 'granted'` ⇒ **未同意、乃至已拒绝
   的用户照样被采集**。改为默认 denied;同时在 `gtag('config')` 之前从
   localStorage 回放一次已存偏好 —— 否则「上一访次同意过」的用户会退化,
   因为 `updateConsentDetailed` 在 `window.gtag` 尚未定义时会被静默丢弃。

② 后台加载 GA。`/admin` 没有 CookieConsent 条,管理员也就没有表达同意的入口,
   但 GA 脚本照常挂载、每次点击都进 dataLayer。新增 `shouldRenderAnalytics()`,
   `/admin*` 返回 null。

判别性测试(各自负对照已做):
- 默认改回 granted ⇒ 「默认 consent 为 denied」转红
- `shouldRenderAnalytics` 改成恒 true ⇒ 「/admin 不加载 GA」转红
- `getDefaultPreferences().analytics` 断言同步改为 false
This commit is contained in:
zhangxiang committed 2026-11-25 09:00:03 +08:00
1 parent b8b7da975d
commit fb14bf70d3
6 files changed
+72 -6

No files matched your search

@@ -89,6 +89,25 @@ describe('GoogleAnalytics', () => {
});
describe('single gtag initialization', () => {
it('默认 consent 为 denied,且在 config 前用已存偏好回放一次 update(DEF-09)', () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');
const { container } = render(<GoogleAnalytics />);
const inline = container.querySelector('script[data-inline="true"]');
const snippet = inline?.textContent ?? '';
// ① 默认必须是拒绝:旧实现把 analytics_storage 默认成 granted ⇒ 未同意的访客也被采集
expect(snippet).toContain("'analytics_storage': 'denied'");
// ② 必须从 localStorage 回放已存偏好,否则上一访次同意过的用户拿不到 granted
expect(snippet).toContain('novalon-cookie-preferences');
// ③ 顺序:update 必须早于 config,否则 config 带着默认拒绝跑掉了
const updateAt = snippet.indexOf("gtag('consent', 'update'");
const configAt = snippet.indexOf("gtag('config'");
expect(updateAt).toBeGreaterThan(-1);
expect(configAt).toBeGreaterThan(-1);
expect(updateAt).toBeLessThan(configAt);
});
it('should send exactly one config from the inline snippet, with default pageview enabled', () => {
setupGtag();
const { GoogleAnalytics } = require('./GoogleAnalytics');