|
| 1 | +import { Env } from '@devmx/shared-api-interfaces/client'; |
| 2 | +import { formatErrorEventForAnalytics } from './utils'; |
| 3 | +import { Injectable } from '@angular/core'; |
| 4 | + |
| 5 | +declare global { |
| 6 | + interface Window { |
| 7 | + dataLayer?: unknown[]; |
| 8 | + gtag?(...args: unknown[]): void; |
| 9 | + } |
| 10 | +} |
| 11 | + |
| 12 | +@Injectable({ providedIn: 'root' }) |
| 13 | +export class AnalyticsService { |
| 14 | + private previousUrl: string | undefined; |
| 15 | + |
| 16 | + constructor(private env: Env) { |
| 17 | + if (env.prod) { |
| 18 | + this.#installGlobalSiteTag(); |
| 19 | + this.#installWindowErrorHandler(); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + reportError(description: string, fatal = true) { |
| 24 | + // Limit descriptions to maximum of 150 characters. |
| 25 | + // See: https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#exd. |
| 26 | + description = description.substring(0, 150); |
| 27 | + |
| 28 | + this.#gtag('event', 'exception', { description: description, fatal }); |
| 29 | + } |
| 30 | + |
| 31 | + locationChanged(url: string) { |
| 32 | + this.#sendPage(url); |
| 33 | + } |
| 34 | + |
| 35 | + #sendPage(url: string) { |
| 36 | + // Won't re-send if the url hasn't changed. |
| 37 | + if (url === this.previousUrl) { |
| 38 | + return; |
| 39 | + } |
| 40 | + this.previousUrl = url; |
| 41 | + } |
| 42 | + |
| 43 | + #gtag(...args: unknown[]) { |
| 44 | + if (window.gtag) { |
| 45 | + window.gtag(...args); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + #installGlobalSiteTag() { |
| 50 | + const url = `https://www.googletagmanager.com/gtag/js?id=${this.env.googleTag}`; |
| 51 | + |
| 52 | + // Note: This cannot be an arrow function as `gtag.js` expects an actual `Arguments` |
| 53 | + // instance with e.g. `callee` to be set. Do not attempt to change this and keep this |
| 54 | + // as much as possible in sync with the tracking code snippet suggested by the Google |
| 55 | + // Analytics 4 web UI under `Data Streams`. |
| 56 | + window.dataLayer = window.dataLayer || []; |
| 57 | + window.gtag = function (...params: unknown[]) { |
| 58 | + window.dataLayer?.push(params); |
| 59 | + }; |
| 60 | + window.gtag('js', new Date()); |
| 61 | + |
| 62 | + // Configure properties before loading the script. This is necessary to avoid |
| 63 | + // loading multiple instances of the gtag JS scripts. |
| 64 | + window.gtag('config', this.env.googleTag); |
| 65 | + |
| 66 | + if (!this.env.prod) { |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + const el = window.document.createElement('script'); |
| 71 | + el.async = true; |
| 72 | + el.src = url; |
| 73 | + window.document.head.appendChild(el); |
| 74 | + } |
| 75 | + |
| 76 | + #installWindowErrorHandler() { |
| 77 | + window.addEventListener('error', (event) => |
| 78 | + this.reportError(formatErrorEventForAnalytics(event), true) |
| 79 | + ); |
| 80 | + } |
| 81 | +} |
0 commit comments