|
| 1 | +/** |
| 2 | + * Extracts the user ID from the Google Analytics device ID. |
| 3 | + * @example `GA1.1.xxxxxxxxxx.xxxxxxxxxx => xxxxxxxxxx-xxxxxxxxxx` |
| 4 | + * @link https://support.google.com/analytics/answer/11397207 |
| 5 | + */ |
| 6 | +function extractGoogleAnalyticsUserIdFromCookie(gaCookie) { |
| 7 | + if (gaCookie) { |
| 8 | + // Remove the Google Analytics tracker from the device ID. |
| 9 | + const userIdParts = gaCookie.split('.').slice(-2); |
| 10 | + if (userIdParts.length === 2) { |
| 11 | + return userIdParts.join('-'); |
| 12 | + } |
| 13 | + } |
| 14 | + return undefined; |
| 15 | +}; |
| 16 | + |
| 17 | +function getBrowserCookie(cookieName) { |
| 18 | + // In React Native environments, `document.cookie` doesn't exist. |
| 19 | + if (typeof document !== 'object' || typeof document.cookie !== 'string') { |
| 20 | + return undefined; |
| 21 | + } |
| 22 | + const name = cookieName + '='; |
| 23 | + const decodedCookie = decodeURIComponent(document.cookie); |
| 24 | + const ca = decodedCookie.split(';'); |
| 25 | + for (let i = 0; i < ca.length; i++) { |
| 26 | + let c = ca[i].trim(); |
| 27 | + if (c.startsWith(name)) { |
| 28 | + return c.substring(name.length); |
| 29 | + } |
| 30 | + } |
| 31 | + return undefined; |
| 32 | +}; |
| 33 | + |
| 34 | +function getGoogleAnalyticsUserIdFromBrowserCookie(cookieName) { |
| 35 | + const browserCookie = getBrowserCookie(cookieName); |
| 36 | + return browserCookie ? extractGoogleAnalyticsUserIdFromCookie(browserCookie) : undefined; |
| 37 | +}; |
| 38 | + |
| 39 | +// make sure the cookie is available when the script first loads, i.e. when the user first visits the website |
| 40 | +const ga_cookie_id = getGoogleAnalyticsUserIdFromBrowserCookie('_ga'); |
| 41 | + |
| 42 | +window.kapaSettings = { user: { uniqueClientId: ga_cookie_id } }; |
0 commit comments