|
/** |
|
* Monitor the GA4 _ga cookie via CookieStore. |
|
* @param {function} onChange - callback(oldValue, newValue) triggered when _ga changes |
|
*/ |
|
function monitorGACookie(onChange) { |
|
if (!("cookieStore"in window)) |
|
return; |
|
|
|
const COOKIE_NAME = "_ga"; |
|
const STORAGE_KEY = "tracked_ga_cookie"; |
|
|
|
// Check if analytics storage consent is granted |
|
function analyticsAllowed() { |
|
try { |
|
const consent = window.google_tag_data?.ics?.entries?.analytics_storage; |
|
return !!(consent?.update || consent?.default || consent?.implicit); |
|
} catch { |
|
return false; |
|
} |
|
} |
|
// Get current cookie value |
|
async function getCurrentGA() { |
|
const cookie = await cookieStore.get(COOKIE_NAME); |
|
return cookie ? cookie.value : null; |
|
} |
|
|
|
// Initialize tracking |
|
(async () => { |
|
if (!analyticsAllowed()) |
|
return; |
|
|
|
const currentValue = await getCurrentGA(); |
|
const storedValue = localStorage.getItem(STORAGE_KEY); |
|
|
|
if (storedValue !== currentValue) { |
|
onChange(storedValue, currentValue); |
|
localStorage.setItem(STORAGE_KEY, currentValue || ""); |
|
} |
|
} |
|
)(); |
|
|
|
// Listen for future changes |
|
cookieStore.addEventListener("change", async (event) => { |
|
if (!analyticsAllowed()) |
|
return; |
|
|
|
for (const cookie of event.changed) { |
|
if (cookie.name === COOKIE_NAME) { |
|
const oldValue = localStorage.getItem(STORAGE_KEY); |
|
const newValue = cookie.value; |
|
if (oldValue !== newValue) { |
|
onChange(oldValue, newValue); |
|
localStorage.setItem(STORAGE_KEY, newValue); |
|
} |
|
} |
|
} |
|
|
|
for (const cookie of event.deleted) { |
|
if (cookie.name === COOKIE_NAME) { |
|
const oldValue = localStorage.getItem(STORAGE_KEY); |
|
onChange(oldValue, null); |
|
localStorage.setItem(STORAGE_KEY, ""); |
|
} |
|
} |
|
} |
|
); |
|
} |