Handle Hotjar consent via local storage

This commit is contained in:
Remi
2025-10-18 14:48:13 +02:00
parent 5fcdef485f
commit 016e8ebe84
3 changed files with 114 additions and 57 deletions

View File

@@ -1,55 +0,0 @@
import { defineNuxtPlugin } from '#app';
import { watch } from 'vue';
import { useCookieConsent } from '~/composables/useCookieConsent';
import { useHotjar } from '#imports';
declare global {
interface Window {
hj?: ((...args: unknown[]) => void) & { q?: unknown[][] };
_hjOptOut?: boolean;
}
}
const setHotjarOptOut = (optOut: boolean) => {
if (typeof window === 'undefined') {
return;
}
window._hjOptOut = optOut;
if (optOut && typeof window.hj === 'function') {
try {
window.hj('event', 'cookie_consent_opt_out');
} catch {
// ignore errors from Hotjar when shutting down
}
}
};
export default defineNuxtPlugin(() => {
if (!import.meta.client) {
return;
}
const { initialize } = useHotjar();
const hasInitialized = useState('hotjar-initialized', () => false);
const { analyticsEnabled } = useCookieConsent();
watch(
() => analyticsEnabled.value,
(enabled) => {
if (enabled) {
setHotjarOptOut(false);
if (!hasInitialized.value) {
initialize();
hasInitialized.value = true;
}
} else {
setHotjarOptOut(true);
hasInitialized.value = false;
}
},
{ immediate: true }
);
});