Skip to content

Commit

Permalink
stops google analytics collection when cookie preference set to false (
Browse files Browse the repository at this point in the history
  • Loading branch information
AimeurAmin authored Dec 23, 2024
1 parent 766f2e4 commit 558aa57
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
46 changes: 46 additions & 0 deletions packages/frontend-utils/src/cookie-consent/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,4 +355,50 @@ describe('useCookieConsent', () => {
expect(uuidv4).not.toHaveBeenCalled();
});
});

it('clears cookies with prefix "_ga" and clears window.dataLayer when analytics is false', async () => {
(Cookies.get as jest.Mock).mockImplementation((name) => {
if (name) {
return JSON.stringify({
cookieId: 'mocked-uuid',
preferences: { essential: true, analytics: false },
});
}
return {
_ga123: 'value1',
_ga456: 'value2',
unrelatedCookie: 'value3',
};
});

const mockRemove = jest.spyOn(Cookies, 'remove');

const originalDataLayer = window.dataLayer;
Object.defineProperty(window, 'dataLayer', {
writable: true,
value: [{ 'gtm.start': new Date().getTime(), event: 'gtm.js' }],
});

const { result } = renderHook(() =>
useCookieConsent({
name: COOKIE_NAME,
baseUrl: apiUrl,
savePath: 'save',
}),
);

await act(async () => result.current.onSaveCookiePreferences(false));

expect(mockRemove).toHaveBeenCalledWith('_ga123');
expect(mockRemove).toHaveBeenCalledWith('_ga456');
expect(mockRemove).not.toHaveBeenCalledWith('unrelatedCookie');

expect(window.dataLayer).toBeDefined();
expect(window.dataLayer).toEqual([]);

Object.defineProperty(window, 'dataLayer', {
writable: true,
value: originalDataLayer,
});
});
});
19 changes: 19 additions & 0 deletions packages/frontend-utils/src/cookie-consent/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ type CookieData = {
};
};

const GA_COOKIES_PREFIX = '_ga';

export const setConsentCookie = (
name: string,
preferences: CookieData,
Expand All @@ -35,6 +37,15 @@ export const hasGivenCookieConsent = (name: string): boolean => {
);
};

export const clearCookiesWithPrefix = (prefix: string): void => {
const allCookies = Cookies.get();
Object.keys(allCookies).forEach((cookieName) => {
if (cookieName.startsWith(prefix)) {
Cookies.remove(cookieName);
}
});
};

export const useCookieConsent = ({
name,
baseUrl,
Expand Down Expand Up @@ -99,6 +110,14 @@ export const useCookieConsent = ({

const onSaveCookiePreferences = async (analytics: boolean) => {
setisSaving(true);
if (!analytics) {
Object.defineProperty(window, 'dataLayer', {
value: [],
writable: true,
});

clearCookiesWithPrefix(GA_COOKIES_PREFIX);
}

const updatedCookieData = {
cookieId:
Expand Down

0 comments on commit 558aa57

Please sign in to comment.