diff --git a/packages/clarity-js/src/core/config.ts b/packages/clarity-js/src/core/config.ts index 818e8d9c..6aaf07be 100644 --- a/packages/clarity-js/src/core/config.ts +++ b/packages/clarity-js/src/core/config.ts @@ -23,6 +23,7 @@ let config: Config = { throttleDom: true, conversions: false, longTask: 30, + limitCookies: false, }; export default config; diff --git a/packages/clarity-js/src/data/metadata.ts b/packages/clarity-js/src/data/metadata.ts index 392b4ef9..52f49606 100644 --- a/packages/clarity-js/src/data/metadata.ts +++ b/packages/clarity-js/src/data/metadata.ts @@ -285,6 +285,12 @@ function getCookie(key: string): string { [isEncoded, decodedValue] = decodeCookieValue(decodedValue); } + // If we are limiting cookies to subdomains, check if it matches the current one + if (config.limitCookies) { + const parts = decodedValue.split(Constant.Tilde); + return parts.length > 1 && parts[1] === location.hostname ? parts[0] : null; + } + return decodedValue; } } @@ -312,6 +318,11 @@ 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) if ((config.track || value == Constant.Empty) && ((navigator && navigator.cookieEnabled) || supported(document, Constant.Cookie))) { + // If we are limiting cookies to subdomains, append the current one to the cookie value + if (config.limitCookies) { + value = `${value}${Constant.Tilde}${location.hostname}`; + } + // Some browsers automatically url encode cookie values if they are not url encoded. // We therefore encode and decode cookie values ourselves. let encodedValue = encodeCookieValue(value); @@ -320,6 +331,13 @@ function setCookie(key: string, value: string, time: number): void { expiry.setDate(expiry.getDate() + time); let expires = expiry ? Constant.Expires + expiry.toUTCString() : Constant.Empty; let cookie = `${key}=${encodedValue}${Constant.Semicolon}${expires}${Constant.Path}`; + + // If we are limiting cookies to subdomains, we only write to the current one. + if (config.limitCookies) { + document.cookie = `${cookie}${Constant.Semicolon}${Constant.Domain}.${location.hostname}`; + return; + } + try { // Attempt to get the root domain only once and fall back to writing cookie on the current domain. if (rootDomain === null) { diff --git a/packages/clarity-js/types/core.d.ts b/packages/clarity-js/types/core.d.ts index a75bb6f2..7731ce33 100644 --- a/packages/clarity-js/types/core.d.ts +++ b/packages/clarity-js/types/core.d.ts @@ -137,6 +137,7 @@ export interface Config { throttleDom?: boolean; conversions?: boolean; longTask?: number; + limitCookies?: boolean; } export const enum Constant {