Load Hotjar after cookie consent

This commit is contained in:
Remi
2025-10-18 13:23:14 +02:00
committed by itsrubberduck
parent 0ea1246221
commit 4fedf69727

View File

@@ -1,3 +1,7 @@
import { defineNuxtPlugin } from '#app';
import { watch } from 'vue';
import { useCookieConsent } from '~/composables/useCookieConsent';
declare global {
interface Window {
hj?: ((...args: unknown[]) => void) & { q?: unknown[][] };
@@ -42,18 +46,54 @@ const appendHotjarScript = () => {
return true;
};
const removeHotjarScript = () => {
const script = document.getElementById(HOTJAR_SCRIPT_ID);
if (script && script.parentNode) {
script.parentNode.removeChild(script);
}
};
const disableHotjar = () => {
if (typeof window === 'undefined') {
return;
}
window._hjOptOut = true;
removeHotjarScript();
window.hj = undefined;
window._hjSettings = undefined;
};
const enableHotjar = () => {
if (typeof window === 'undefined') {
return false;
}
window._hjOptOut = false;
ensureHotjarStub();
return appendHotjarScript();
};
export default defineNuxtPlugin(() => {
if (!import.meta.client) {
return;
}
const hasLoaded = useState('hotjar-loaded', () => false);
const { analyticsEnabled } = useCookieConsent();
if (!hasLoaded.value) {
ensureHotjarStub();
if (appendHotjarScript()) {
hasLoaded.value = true;
}
}
watch(
() => analyticsEnabled.value,
(enabled) => {
if (enabled) {
if (enableHotjar()) {
hasLoaded.value = true;
}
} else {
disableHotjar();
hasLoaded.value = false;
}
},
{ immediate: true }
);
});