From 8f23517e4dd15df75895fc2b6f33bcb94cad3767 Mon Sep 17 00:00:00 2001 From: Miguel Monteiro Claveri Date: Wed, 3 Apr 2024 14:27:44 +0200 Subject: [PATCH] Add removeCookie functionality instead of re-using "setCookie" with max number --- packages/clarity-js/src/data/metadata.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/clarity-js/src/data/metadata.ts b/packages/clarity-js/src/data/metadata.ts index 85a43348..58ef1e48 100644 --- a/packages/clarity-js/src/data/metadata.ts +++ b/packages/clarity-js/src/data/metadata.ts @@ -110,8 +110,8 @@ export function id(): string { export function consent(status: boolean = true): void { if (!status) { config.track = false; - setCookie(Constant.SessionKey, Constant.Empty, -Number.MAX_VALUE); - setCookie(Constant.CookieKey, Constant.Empty, -Number.MAX_VALUE); + removeCookie(Constant.SessionKey); + removeCookie(Constant.CookieKey); clarity.stop(); window.setTimeout(clarity.start, Setting.RestartDelay); return; @@ -279,6 +279,20 @@ function encodeCookieValue(value: string): string { return encodeURIComponent(value); } +function removeCookie(key: string): void{ + // only erase cookies if we are currently in a cookie writing mode (and they are supported) + // OR if we are trying to write an empty cookie (i.e. clear the cookie value out) + if ((config.track || value == Constant.Empty) && ((navigator && navigator.cookieEnabled) || supported(document, Constant.Cookie))) { + let expirationDate = new Date("1970-01-01T00:00:000Z"); + + let expires = Constant.Expires + expirationDate.toUTCString(); + let encodedValue = encodeCookieValue(""); + let cookie = `${key}=${encodedValue}${Constant.Semicolon}${expires}${Constant.Path}`; + + document.cookie = cookie; + } +} + function setCookie(key: string, value: string, time: number): void { // only write cookies if we are currently in a cookie writing mode (and they are supported) // OR if we are trying to write an empty cookie (i.e. clear the cookie value out)