From 7ffc56bcdc84e43606fbaa5844d43400d8731560 Mon Sep 17 00:00:00 2001 From: Ben Hong Date: Fri, 8 Mar 2024 12:48:24 -0800 Subject: [PATCH] fix(docs-infra): add cookie consent gtag event default state This PR sets a default state for cookie consent of 'denied'. The other part of the PR exists in the angular/dev-infra repo which will grant permission when the user accepts the cookie banner. --- .../services/analytics/analytics.service.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/adev/src/app/core/services/analytics/analytics.service.ts b/adev/src/app/core/services/analytics/analytics.service.ts index 74d2483c23922..033121eee8756 100644 --- a/adev/src/app/core/services/analytics/analytics.service.ts +++ b/adev/src/app/core/services/analytics/analytics.service.ts @@ -8,7 +8,7 @@ import {inject, Injectable} from '@angular/core'; -import {WINDOW, ENVIRONMENT} from '@angular/docs'; +import {WINDOW, ENVIRONMENT, LOCAL_STORAGE, STORAGE_KEY, setCookieConsent} from '@angular/docs'; import {formatErrorEventForAnalytics} from './analytics-format-error'; @@ -28,6 +28,7 @@ interface WindowWithAnalytics extends Window { export class AnalyticsService { private environment = inject(ENVIRONMENT); private window: WindowWithAnalytics = inject(WINDOW); + private readonly localStorage = inject(LOCAL_STORAGE); constructor() { this._installGlobalSiteTag(); @@ -64,6 +65,21 @@ export class AnalyticsService { window.gtag = function () { window.dataLayer?.push(arguments); }; + + // Cookie banner consent initial state + // This code is modified in the @angular/docs package in the cookie-popup component. + // Docs: https://developers.google.com/tag-platform/security/guides/consent + if (this.localStorage) { + if (this.localStorage.getItem(STORAGE_KEY) === 'true') { + setCookieConsent('granted'); + } else { + setCookieConsent('denied'); + } + } else { + // In case localStorage is not available, we default to denying cookies. + setCookieConsent('denied'); + } + window.gtag('js', new Date()); // Configure properties before loading the script. This is necessary to avoid