Skip to content

Commit

Permalink
fix(docs-infra): add cookie consent gtag event default state (#54574)
Browse files Browse the repository at this point in the history
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.

PR Close #54574
  • Loading branch information
bencodezen authored and AndrewKushnir committed Apr 25, 2024
1 parent 44c0ed8 commit dcf737e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
Expand Up @@ -7,8 +7,9 @@
*/

import {Injector} from '@angular/core';
import {ENVIRONMENT, WINDOW} from '@angular/docs';
import {ENVIRONMENT, WINDOW, LOCAL_STORAGE} from '@angular/docs';
import {AnalyticsService} from './analytics.service';
import {MockLocalStorage} from '@angular/docs/testing';

describe('AnalyticsService', () => {
let service: AnalyticsService;
Expand All @@ -18,6 +19,7 @@ describe('AnalyticsService', () => {
let windowOnErrorHandler: (event: ErrorEvent) => void;

let mockWindow: any;
let mockLocalStorage = new MockLocalStorage();

beforeEach(() => {
gtagSpy = jasmine.createSpy('gtag');
Expand All @@ -39,6 +41,7 @@ describe('AnalyticsService', () => {
{provide: ENVIRONMENT, useValue: {}},
{provide: AnalyticsService, deps: [WINDOW]},
{provide: WINDOW, useFactory: () => mockWindow, deps: []},
{provide: LOCAL_STORAGE, useValue: mockLocalStorage},
],
});

Expand Down
18 changes: 17 additions & 1 deletion adev/src/app/core/services/analytics/analytics.service.ts
Expand Up @@ -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';

Expand All @@ -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();
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit dcf737e

Please sign in to comment.