如何使用 angular universal ssr 添加谷歌分析跟踪

问题描述 投票:0回答:2

我正在开发一个有角度的通用 SSR 应用程序,想为页面浏览量添加 Google Analytics 跟踪,但无法让它工作。

我尝试过的大多数软件包都无法与 SSR 一起使用,因为它们试图直接访问窗口/文档。

最终我得到了一个我想分享的相当基本的解决方案。

angular google-analytics angular-universal server-side-rendering
2个回答
11
投票

通过导入 isPlatformBrowser 你可以指定你只想在客户端执行的代码。然后你可以附加适当的脚本标签进行谷歌分析跟踪。

import { isPlatformBrowser } from '@angular/common';
import { Component, ElementRef, Inject, PLATFORM_ID, Renderer2 } from '@angular/core';
import { environment } from '../../environments/environment';

@Component({
  selector: 'app-google-analytics-gtag',
  template: '',
})
export class GoogleAnalyticsGTagComponent {
  trackingCode = environment.googleAnalyticsTrackingCode;

  constructor(
    @Inject(PLATFORM_ID) private readonly platformId: Object,
    private readonly renderer: Renderer2,
    private readonly el: ElementRef,
  ) {
    // BROWSER
    if (isPlatformBrowser(this.platformId)) {
      const script = this.renderer.createElement('script') as HTMLScriptElement;
      script.src = `//www.googletagmanager.com/gtag/js?id=${this.trackingCode}`;
      script.async = true;
      this.renderer.appendChild(this.el.nativeElement, script);

      const script2 = this.renderer.createElement('script') as HTMLScriptElement;
      const scriptBody = this.renderer.createText(`
        window.dataLayer = window.dataLayer || [];
        function gtag() {
          dataLayer.push(arguments);
        }
        gtag('js', new Date());

        gtag('config', '${this.trackingCode}');
      `);
      this.renderer.appendChild(script2, scriptBody);
      this.renderer.appendChild(this.el.nativeElement, script2);
    }
  }
}

0
投票

另一种使用基于 Cris Putnam 答案的文档的替代方法:

import { DOCUMENT, isPlatformBrowser } from '@angular/common';
import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { ConfigService } from '../services/config.service';

@Component({
  selector: 'app-google-analytics-gtag',
  template: '',
})
export class GoogleAnalyticsGTagComponent {
  constructor(
    private configService: ConfigService,
    @Inject(PLATFORM_ID) private readonly platformId: Object,
    @Inject(DOCUMENT) private document: Document
  ) {
    const gaTrackId = this.configService.getGoogleAnalyticsTrackId();
    const debugMode = this.configService.getGoogleAnalyticsDebugMode();
    // BROWSER
    if (isPlatformBrowser(this.platformId)) {
      const scriptGtag = this.document.createElement('script') as HTMLScriptElement;
      scriptGtag.src = `//www.googletagmanager.com/gtag/js?id=${gaTrackId}`;
      scriptGtag.async = true;
      this.document.head.appendChild(scriptGtag);

      const scriptInit = this.document.createElement('script') as HTMLScriptElement;
      const scriptBody = this.document.createTextNode(`
        window.dataLayer = window.dataLayer || [];
        function gtag() {
          dataLayer.push(arguments);
        }
        gtag('js', new Date());
        gtag('config', '${gaTrackId}', { debug_mode: ${debugMode} });
      `);

      scriptInit.appendChild(scriptBody);
      this.document.head.appendChild(scriptInit);
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.