You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular 18 SSR项目中正确集成Usercentrics Cookiebot?

Angular 18 SSR 集成 Usercentrics Cookiebot 完整解决方案

一、基础集成适配 SSR

不要直接在index.html硬编码Usercentrics脚本,避免SSR渲染阶段触发异常,改用Angular服务动态加载(仅在客户端执行):

  1. 创建cookie-consent.service.ts:
import { Injectable, Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable({ providedIn: 'root' })
export class CookieConsentService {
  constructor(
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document: Document
  ) {}

  loadUsercentrics(): void {
    const script = this.renderer.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://app.usercentrics.eu/browser-ui/latest/loader.js';
    script.setAttribute('data-settings-id', '你的Usercentrics设置ID');
    script.async = true;
    this.renderer.appendChild(this.document.body, script);
  }
}
  1. 在app.component.ts中仅客户端加载:
import { Component, OnInit, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { PLATFORM_ID } from '@angular/core';
import { CookieConsentService } from './cookie-consent.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
    private cookieConsentService: CookieConsentService
  ) {}

  ngOnInit(): void {
    if (isPlatformBrowser(this.platformId)) {
      this.cookieConsentService.loadUsercentrics();
    }
  }
}

二、修复YouTube播放器被移除问题

用nocookie.youtube.com仍被拦截,是因为Usercentrics默认会处理所有第三方嵌入,按以下方式调整:

  1. 后台配置(推荐):

    • 进入Usercentrics控制台,找到「内容拦截」设置
    • 为YouTube添加自定义规则,匹配https://www.youtube-nocookie.com/embed/*,设置为「始终允许」(nocookie版本无Cookie,符合法规)
  2. 前端手动控制:
    监听同意状态,拒绝时强制保留iframe:

ngOnInit(): void {
  if (isPlatformBrowser(this.platformId)) {
    window.addEventListener('ucEvent', (event: any) => {
      if (event.type === 'consentUpdated') {
        const youtubeIframes = document.querySelectorAll('iframe[src*="youtube-nocookie.com"]');
        youtubeIframes.forEach(iframe => {
          // 无论同意状态,都显示nocookie播放器
          iframe.style.display = 'block';
        });
      }
    });
  }
}

三、解决Google Analytics gtag Cookie残留问题

禁用同意后仍有Cookie,是因为gtag提前加载或未绑定同意状态:

  1. 移除硬编码的gtag脚本:删掉index.html中所有gtag相关代码
  2. 动态初始化gtag:在服务中根据同意状态加载:
initGoogleAnalytics(): void {
  window.addEventListener('ucEvent', (event: any) => {
    const consentStatus = event.detail.consent.statuses.GoogleAnalytics;
    if (consentStatus === 'GRANTED') {
      // 加载gtag并初始化
      const script = this.renderer.createElement('script');
      script.src = 'https://www.googletagmanager.com/gtag/js?id=你的GA跟踪ID';
      script.async = true;
      this.renderer.appendChild(this.document.body, script);

      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', '你的GA跟踪ID');
    } else {
      // 拒绝时清除GA相关Cookie
      const gaCookies = ['_ga', '_gid', '_gat', '_ga_*'];
      gaCookies.forEach(cookieName => {
        document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
      });
    }
  });
}
  1. 在app.component.ts的ngOnInit中调用this.initGoogleAnalytics()(仅客户端)

四、通用SSR注意事项

  • 所有Cookie相关逻辑必须用isPlatformBrowser判断,仅在客户端执行
  • 依赖Usercentrics的ucEvent事件监听同意状态变化,支持用户随时修改设置
  • TikTok、Facebook等第三方服务遵循同样逻辑:拒绝时不加载脚本/iframe,同意后动态初始化

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 08:52:15